Couldnt bind color to LinearGradientBrush

525 views Asked by At

I'm trying this in collection view and i want each item with a different color so I have bound color to GradientStop in xaml like this:

<BoxView.Background>
    <LinearGradientBrush EndPoint="0,1">
        <GradientStop Color="{Binding gradient_start_color}" Offset="0.1" />
        <GradientStop Color="{Binding gradient_stop_color}" Offset="1.0" />
    </LinearGradientBrush>
</BoxView.Background>

But the color is not bound and by default i get transparent background. Is there a way to bind gradientstop color?

1

There are 1 answers

2
Cfun On BEST ANSWER

This is a known bug in Xamarin.Forms https://github.com/xamarin/Xamarin.Forms/issues/12339, the workaround mentioned there is to change it in the code-behind rather than using data binding in xaml.

<BoxView x:Name="boxView" ...>
Color gradient_start_color;
Public Color Gradient_start_color
{
   get => gradient_start_color;
   set
   {
       gradient_start_color = value;
       PropertyChanged();
       UpdateBoxViewBackground();
   };
}

Color gradient_stop_color;
Public Color Gradient_stop_color
{
   get => gradient_stop_color;
   set
   {
       gradient_stop_color = value;
       PropertyChanged();
       UpdateBoxViewBackground();
   };
}

UpdateBoxViewBackground()
{
    (boxView.Background as LinearGradientBrush).GradientStops[0].Color = Gradient_start_color;
    (boxView.Background as LinearGradientBrush).GradientStops[1].Color = Gradient_stop_color;
}

Constructor()
{
var background = new LinearGradientBrush
{
    EndPoint = new Point(0, 1),
    GradientStops = new GradientStopCollection
    {
        new GradientStop { Color = Gradient_start_color, Offset = 0.1f },
        new GradientStop { Color = Gradient_stop_color, Offset = 1.0f }
    }
};
boxView.Background = background;
}