1

I want to have a markup extension called RgbColorExtension where R property is bindable to let me adjust its value with a slider.

The following attempt does not work. Changing the slider does not effect the R property.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="Sandbox.MainPage"
             xmlns:local="clr-namespace:Sandbox"
             >
    <VerticalStackLayout>
        <Slider x:Name="slider" Maximum="1"/>
        <Label Text="{Binding Value,Source={x:Reference slider}}"/>
        <BoxView HeightRequest="200" WidthRequest="200">
            <BoxView.Color>
                <local:RgbColor R="{Binding Value,Source={x:Reference slider}}" G="0" B="0" A="0.5"/>
            </BoxView.Color>
        </BoxView>
        <BoxView 
            HeightRequest="200" 
            WidthRequest="200"
            Color="{local:RgbColor R={Binding Value,Source={x:Reference slider}},G=0.5,B=0.5,A=.5}"
            />
    </VerticalStackLayout>

</ContentPage>

namespace Sandbox;

public class RgbColorExtension : BindableObject, IMarkupExtension<Color>
{

    public static readonly BindableProperty RProperty =
        BindableProperty.Create(nameof(R), typeof(float), typeof(RgbColorExtension), 0.5f);

    public float R
    {
        get => (float)GetValue(RProperty);
        set => SetValue(RProperty, value);
    }


    public float G { get; set; }
    public float B { get; set; }
    public float A { get; set; }


    public Color ProvideValue(IServiceProvider serviceProvider)
    {
        return Color.FromRgba(R, G, B, A);
    }

    object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider)
    {
        return (this as IMarkupExtension<Color>).ProvideValue(serviceProvider);
    }
}

What am I missing here?

  • I think Maui doesn't "know" to call `ProvideValue` again. `RProperty` needs a `propertyChanged` action, that invokes an event handler, that triggers `BoxView.Color` to re-evaluate (thus calling ProvideValue). Sorry, it isn't coming to mind how to do that in a MarkupExtension; perhaps someone else can carry this further... [Maybe a trigger could be added to the XAML, but that ruins the "simplicity" of your approach.] – ToolmakerSteve Nov 04 '22 at 18:32
  • You can check this [doc](https://learn.microsoft.com/en-us/dotnet/maui/xaml/fundamentals/mvvm?view=net-maui-7.0#interactive-mvvm), it talks how to change color by MVVM. – Jianwei Sun - MSFT Nov 09 '22 at 07:00

0 Answers0