How do you color a rectangle in C# that has been declared in XAML in WPF?
There is a rectangle control in XAML. In my C# code there are times in which it would be nice to fill the background color. How does one do this?
For all the lazy programmers, the .net color enums:
myRectangle.Fill = new SolidColorBrush(System.Windows.Media.Colors.AliceBlue);
Assuming you named your rectangle myRectangle, you can color it using the Fill property:
myRectangle.Height = 200;
myRectangle.Width = 200;
myRectangle.Stroke = new SolidColorBrush(Color.FromRgb(0, 111, 0));
myRectangle.Fill = new SolidColorBrush(Color.FromRgb(0, 111, 111));
Rectangle Colour in XAML for Windows Phone:
<Rectangle Width="480" Height="200">
<Rectangle.Fill>
<SolidColorBrush Color="Azure" />
</Rectangle.Fill>
</Rectangle>
Wpf binding would be able to do this without having to reference the control by name in code:
<Rectangle Width="480" Height="200" Fill="{Binding Path=FillColor}"/>
Then put a property on your DataContext class, assuming you have implemented INotifyPropertyChanged:
public Brush FillColor
{
get { return this.fillColor; }
set
{
this.fillColor = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Then you can assign your required color to the FillColor property and the UI will update itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With