【问题标题】:C# WPF Rectangle Fill BindingC# WPF 矩形填充绑定
【发布时间】:2017-04-27 11:49:22
【问题描述】:

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

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);
    }
}

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

【问题讨论】:

  • 不要使用Color,而是使用SolidColorBrush
  • 你设置了DataContext吗?如果您在 Xaml 中对颜色进行硬编码,您能看到矩形吗?
  • @FelixD。 - 使用Brush 代替 od Color 帮助:) @MartinoBordin - 是的,如果我在 xaml 中设置颜色,我可以看到矩形,但它不符合我的需要 - 颜色必须动态更改。不,我没有在这个rectangle 中设置数据上下文。

标签: c# wpf xaml mvvm caliburn.micro


【解决方案1】:

另一种方法是使用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}}"/>

【讨论】:

    【解决方案2】:

    Rectangle.Fill(它继承自Shape)是Brush,而不是Color。因此,请将您的财产改为Brush

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

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

    【讨论】:

    • 谢谢 - 它工作正常,没有更多问题......到目前为止:)
    • @JaroslawMatlak “到目前为止没有更多问题”是我们任何人在这个球拍中能说的最好的话。祝你好运!
    【解决方案3】:

    我对 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;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 2012-05-10
      • 2015-08-20
      • 2012-02-02
      • 1970-01-01
      相关资源
      最近更新 更多