C# WPF 矩形填充绑定(bind)

标签 c# wpf xaml mvvm caliburn.micro

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

XAML:

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

View 模型:

public ItemViewModel()
{
     Colorr = Colors.Red;;
}
public Color Colorr
{
    get {
        return color; }
    set
    {
        color = 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}}"/>

关于C# WPF 矩形填充绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41103795/

相关文章:

c# - 可以同时执行 WebForms 和 MVC 的最佳模拟框架?

C# 在运行时从泛型类型查找方法重载

c# - 调用派生类的构造函数先于基类的构造函数执行

c# - 如何将 CustomControl 属性绑定(bind)到控件本身?

c# - 将 Windows 主题更改为高对比度时,将按钮颜色更改为白色

c# - 有没有人对 10Gen 支持的 c# 驱动程序有问题

c# - 在 MVVM 之后创建 WPF View 时将数据传递给 ViewModel

wpf - 无法访问 app.xaml 中定义的资源

c# - 在程序运行时编译/执行 XAML

c# - 将对象图写入 XAML 时出现 StackOverFlow 异常