C# WPF 矩形填充绑定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41103795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# WPF Rectangle Fill Binding
提问by Jaroslaw Matlak
I need to bind color to fill the rectangle.
我需要绑定颜色来填充矩形。
XAML:
XAML:
<Rectangle Fill="{Binding Colorr}"
VerticalAlignment="Center"
Height="3" Width="16"
Margin="3, 1, 5, 0"
Visibility="Visible"/>
ViewModel:
视图模型:
public ItemViewModel()
{
Colorr = Colors.Red;;
}
public Color Colorr
{
get {
return color; }
set
{
color = value;
NotifyOfPropertyChange(() => Colorr);
}
}
The resulting rectangle is not visible (or is transparent - it's hard to say...) instead of being visible and red. How can I get rid of this problem?
生成的矩形不可见(或者是透明的 - 很难说......)而不是可见和红色。我怎样才能摆脱这个问题?
回答by 15ee8f99-57ff-4f92-890c-b56153
Rectangle.Fill(which it inherits from Shape) is a Brush, not a Color. So make your property a Brushinstead:
Rectangle.Fill(它继承自Shape)是一个Brush,而不是一个Color。因此,将您的财产Brush改为:
private Brush _colorr = Brushes.Red;
public Brush Colorr
{
get
{
return _colorr;
}
set
{
_colorr = value;
NotifyOfPropertyChange(() => Colorr);
}
}
There may be other problems, but you need to fix this one first.
可能还有其他问题,但您需要先解决这个问题。
回答by Vidas Vasiliauskas
The other way around is to use ColorToBrushConverter, just like the one below:
另一种方法是使用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;
}
}
Then in XAML define the converter as resource and use it like this:
然后在 XAML 中将转换器定义为资源并像这样使用它:
<Rectangle Fill="{Binding Colorr, Converter={StaticResource ColorToBrushConverter}}"/>

