无法将颜色绑定到 LinearGradientBrush

时间:2021-05-08 12:47:23

标签: xaml xamarin xamarin.forms linear-gradients lineargradientbrush

我正在集合视图中尝试此操作,我希望每个项目具有不同的颜色,因此我在 xaml 中将颜色绑定到 GradientStop,如下所示:

<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>

但是颜色不受限制,默认情况下我会得到透明背景。有没有办法绑定gradientstop颜色?

1 个答案:

答案 0 :(得分:0)

这是 Xamarin.Forms https://github.com/xamarin/Xamarin.Forms/issues/12339 中的一个已知错误,其中提到的解决方法是在代码隐藏中更改它,而不是在 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;
}
相关问题