C# WPF 矩形填充绑定

C# WPF Rectangle Fill Binding

我需要绑定颜色来填充矩形。

XAML:

<Rectangle Fill="{Binding Colorr}"
           VerticalAlignment="Center"
           Height="3" Width="16"
           Margin="3, 1, 5, 0" 
           Visibility="Visible"/>

视图模型:

public ItemViewModel()
{
     Colorr = Colors.Red;;
}
public Color Colorr
{
    get {
        return color; }
    set
    {
        color = value;
        NotifyOfPropertyChange(() => Colorr);
    }
}

生成的矩形是不可见的(或者是透明的 - 很难说......)而不是可见的和红色的。我怎样才能摆脱这个问题?

Rectangle.Fill(它继承自 Shape)是 Brush,而不是 Color。所以让你的属性变成Brush

private Brush _colorr = Brushes.Red;
public Brush Colorr
{
    get
    {
        return _colorr;
    }
    set
    {
        _colorr = value;
        NotifyOfPropertyChange(() => Colorr);
    }
}

可能还有其他问题,但您需要先解决这个问题。

另一种方法是使用 ColorToBrushConverter,如下所示:

 using System.Windows.Data;
 using System.Windows.Media;

 public class ColorToBrushConverter : IValueConverter
 {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return new SolidColorBrush((Color)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value as SolidColorBrush).Color;
        }
 }

然后在XAML中将转换器定义为资源并像这样使用它:

<Rectangle Fill="{Binding Colorr, Converter={StaticResource ColorToBrushConverter}}"/>

我对 Vaidas 提出的 Color BrushConverter 做了一些小改动,以处理可能的空引用异常:

using System.Windows.Data;
using System.Windows.Media;
    
    namespace Common.Client.Wpf.Converters
{
    public class ColorToBrushConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value is null ? null : new SolidColorBrush((Color)value);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (value as SolidColorBrush)?.Color;
        }
    }
}