C# WPF Rectangle Fill Binding
11,708
Solution 1
Rectangle.Fill
(which it inherits from Shape
) is a Brush
, not a Color
. So make your property a Brush
instead:
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.
Solution 2
The other way around is to use ColorToBrushConverter
, just like the one below:
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:
<Rectangle Fill="{Binding Colorr, Converter={StaticResource ColorToBrushConverter}}"/>
Comments
-
Jaroslaw Matlak almost 2 years
I need to bind color to fill the rectangle.
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?
-
Jaroslaw Matlak over 7 yearsThank you - it works and there are no more problems... so far :)
-
15ee8f99-57ff-4f92-890c-b56153 over 7 years@JaroslawMatlak "No more problems so far" is the best any of us can ever say in this racket. Good luck!