Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you color a rectangle in C# that has been declared in XAML in WPF?

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?

like image 216
xarzu Avatar asked May 22 '10 01:05

xarzu


4 Answers

For all the lazy programmers, the .net color enums:

myRectangle.Fill = new SolidColorBrush(System.Windows.Media.Colors.AliceBlue); 
like image 163
Metanoia Avatar answered Nov 14 '22 05:11

Metanoia


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));
like image 31
Brian R. Bondy Avatar answered Nov 14 '22 04:11

Brian R. Bondy


Rectangle Colour in XAML for Windows Phone:

<Rectangle Width="480" Height="200">
    <Rectangle.Fill>
        <SolidColorBrush Color="Azure" />
    </Rectangle.Fill>
</Rectangle>
like image 20
David Douglas Avatar answered Nov 14 '22 03:11

David Douglas


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.

like image 33
benPearce Avatar answered Nov 14 '22 05:11

benPearce