WPF Color Palatte using the Brush and Brush Converter classes

Posted by: Mahesh Sabnis , on 8/13/2010, in Category WPF
Views: 49396
Abstract: The ‘System.Windows.Media’ namespace provides useful types like Brush, Brushes, SolidColorBrush, VisualBrush etc. that enable integration of rich media, including drawings, text, and audio/video content in Windows Presentation Foundation (WPF) applications.
The ‘System.Windows.Media’ namespace provides useful types like Brush, Brushes, SolidColorBrush, VisualBrush etc. that enable integration of rich media, including drawings, text, and audio/video content in Windows Presentation Foundation (WPF) applications. One of the most important classes provided in this namespace is the ‘BrushConverter’. This class converts the color name (string) to a Brush object. The ‘Brushes’ class contains all the colors as public properties. Using reflection these properties can be accessed as demoed in this article.
Step 1: Open VS2008/VS2010 and create a new WPF application, name it as ‘WPF_ColorPalate’.
Step 2: In the Window1.Xaml write the xaml following code:
<Grid>
 <ListBox Height="230" Margin="32,19,345,0"Name="listBox1" VerticalAlignment="Top" SelectionChanged="listBox1_SelectionChanged" />
 <Button Content="Button" Height="58" HorizontalAlignment="Left" Margin="372,42,0,0" Name="button1" VerticalAlignment="Top" Width="151" />
</Grid>
 
Step 3: In the Loaded event of the window, write the following C# code:
C#
private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Type t = typeof(System.Windows.Media.Brushes);
            PropertyInfo[] colors = t.GetProperties();
 
            foreach (PropertyInfo pColor in colors)
            {
 
                StackPanel stkPnl = new StackPanel();
                stkPnl.Width = listBox1.Width; 
                stkPnl.Orientation = Orientation.Horizontal;
 
                TextBlock txtColName = new TextBlock();
                txtColName.Text = pColor.Name;
                txtColName.Width = 100;
                txtColName.Height = 20;
                Rectangle rectColor = new Rectangle();
 
                BrushConverter converter = new BrushConverter();
                Brush brush = converter.ConvertFromString(pColor.Name) as Brush;
                rectColor.StrokeThickness = 6;
                rectColor.Fill = brush;
                rectColor.Width = 60;
 
                stkPnl.Children.Add(txtColName);
                stkPnl.Children.Add(rectColor);
                ListBoxItem item = new ListBoxItem();
                item.Content = stkPnl;
 
                listBox1.Items.Add(item);
            }
        }
 
 
VB.NET (Converted Code)
Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
                  Dim t As Type = GetType(System.Windows.Media.Brushes)
                  Dim colors() As PropertyInfo = t.GetProperties()
 
                  For Each pColor As PropertyInfo In colors
 
                        Dim stkPnl As New StackPanel()
                        stkPnl.Width = listBox1.Width
                        stkPnl.Orientation = Orientation.Horizontal
 
                        Dim txtColName As New TextBlock()
                        txtColName.Text = pColor.Name
                        txtColName.Width = 100
                        txtColName.Height = 20
                        Dim rectColor As New Rectangle()
 
                        Dim converter As New BrushConverter()
                        Dim brush_Renamed As Brush = TryCast(converter.ConvertFromString(pColor.Name), Brush)
                        rectColor.StrokeThickness = 6
                        rectColor.Fill = brush_Renamed
                        rectColor.Width = 60
 
                        stkPnl.Children.Add(txtColName)
                        stkPnl.Children.Add(rectColor)
                        Dim item As New ListBoxItem()
                        item.Content = stkPnl
 
                        listBox1.Items.Add(item)
                  Next pColor
End Sub
 
The above code, uses reflection to read all color properties from the ‘Brushes’ class. By iterating the properties, the code reads the name of every color. In the ListBox, ListItem is added which contains TextBlock for color name and Rectangle of which fill property is set using BrushConverter class and its ‘ConvertFromString()’ method.
Step 4: Now to select the color from the ListBox and set it as a background property of the button, write the following code in ‘SelectionChanged’ event of the ListBox.
Since ListBox contains ListBoxItem and also a StackPanel with TextBlock and Rectangle as its children, the ‘foreach’ loop with UIELement object is used. This loop locates the rectangle and using its ‘Fill’ property, extracts Brush object, using which the background property of the button is set.
C#
private void listBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
ListBoxItem lstItem = listBox1.SelectedItem as ListBoxItem;
StackPanel stkPnl = lstItem.Content as StackPanel;
 
foreach (UIElement ele in stkPnl.Children)
{
if (ele.GetType() == typeof(Rectangle))
{
button1.Background = ((Rectangle)ele).Fill;
}
}
}
 
VB.NET (Converted code)
Private Sub listBox1_SelectionChanged(ByVal sender As Object, ByVal e As SelectionChangedEventArgs)
                  Dim lstItem As ListBoxItem = TryCast(listBox1.SelectedItem, ListBoxItem)
                  Dim stkPnl As StackPanel = TryCast(lstItem.Content, StackPanel)
 
                  For Each ele As UIElement In stkPnl.Children
                        If ele.GetType() Is GetType(Rectangle) Then
                              button1.Background = (CType(ele, Rectangle)).Fill
                        End If
                  Next ele
End Sub
 
Step 5: Run the application and select color from the ListBox. The following result will be displayed:
ListBox    
Conclusion:
WPF provides easy to use mechanism to work with media brush features using Brush and BrushConverter classes.

This article has been editorially reviewed by Suprotim Agarwal.

Absolutely Awesome Book on C# and .NET

C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.

We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).

Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.

Click here to Explore the Table of Contents or Download Sample Chapters!

What Others Are Reading!
Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+

Author
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @maheshdotnet or connect with him on LinkedIn


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!