Monday, March 7, 2011

Colors and Brushes in wpf

Colors class and Brushes class provides a collection of static read-only properties with all the named colors.

Notice the names are in plural. But Brushes provide return objects of type SolidColorBrush. Instead of setting the Background property like this:

Background = new SolidColorBrush(Colors.PaleGoldenrod);

you can use this:

Background = Brushes.PaleGoldenrod;

Although these two statements will certainly color your window background with the same color, there is a difference between the two approaches that reveals itself in a program like VaryTheBackground. In that program try replacing the following field definition:

SolidColorBrush brush = new SolidColorBrush(Colors.Black);


with

SolidColorBrush brush = Brushes.Black;


And when you do:

brush.Color = clr; 


In second case, you will get an Invalid Operation Exception that states "Cannot set a property on object '#FF000000' because it is in a read-only state." The problem is the very last statement in the OnMouseMove method, which attempts to set the Color property of the brush. (The hexadecimal number quoted in the exception is the current value of the Color property.)

Read more about Brushes : http://msdn.microsoft.com/en-us/library/system.windows.media.brushes.aspx

No comments:

Post a Comment