Confessions of a .NET Developer!

List all the Colors in WPF

Here I am going to make a WPF application that will list all the colors together with its HEX and its RGB value.

Here is how the Application will look like :

ColorWindow

ColorWindow

Here is the code-behind :

    public partial class ListTheColors : Window
    {
        public ListTheColors()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(ListTheColors_Loaded);
        }

        void ListTheColors_Loaded(object sender, RoutedEventArgs e)
        {           
            listColors.ItemsSource = typeof(Colors).GetProperties();
        }
    }

So here I am using Reflection to get the Properties in the Colorsclass.
The GetProperties() function will return an array of PropertyInfo which is set as ItemsSource to our ListBox.
The PropertyInfo will contain all the Public Properties of the class Colors.
We will extract the name property from it, as it will contain the name of the Color.

Lets move over to the XAML of our application :
Firstly lets specify the DataTemplate for the ListBox which is defined in the Grid.Resources

    <Grid>
        <Grid.Resources>
            <local:BrushToHexConverter x:Key="conv"/>

            <DataTemplate x:Key="BoxTemplate">
                <StackPanel Orientation="Horizontal">
                    <Border Background="{Binding Path=Name}"
                            CornerRadius="5"
                            Width="50"
                            Height="50"/>
                    <StackPanel Orientation="Vertical" Margin="5">
                        <TextBlock Text="{Binding Path=Name}" Margin="5"/>
                        <TextBlock Text="{Binding Path=Name,Converter={StaticResource conv}}" Margin="2"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>

So the Border’s background is painted by extracting the Name property which in turn contains the name of the Color.
The first TextBlock displays the name of the Color and the second displays the A,R,G and B of the Color.
The second TextBlock’s uses a Converter to do its job which will convert the Color to RGB values.
Here is the Converter class named BrushToHexConverter which implements IValueConverter interface.

    class BrushToHexConverter:IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            String colorName = value.ToString();
            BrushConverter conv = new BrushConverter();
            SolidColorBrush brush = conv.ConvertFromString(colorName) as SolidColorBrush;
            Color color = brush.Color;
            StringBuilder buildString = new StringBuilder();
                buildString.AppendLine(brush.ToString()).Append("A: ").Append(color.A).Append("  R:").Append(color.R).Append("  G:").Append(color.G).Append("  B:").Append(color.B);
            return buildString;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

We use a BrushConverter class to extract the color using the ConvertFromString function which takes the name of the color(for ex. AliceBlue) and converts it to a Brush and use the Color property of the Brush to get the Color.
From that color we can extract the A,R,G and B values.

Next I have used a Style for each ListBoxItem.

            <Style x:Key="ItemStyle" TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Border CornerRadius="2" 
                                    Margin="3"
                                    BorderBrush="Gray"
                                    BorderThickness="2">
                                <ContentPresenter Margin="2"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>

Here is the full XAML :

    <Grid>
        <Grid.Resources>

            <local:BrushToHexConverter x:Key="conv"/>
            
            <DataTemplate x:Key="BoxTemplate">
                <StackPanel Orientation="Horizontal">
                    <Border Background="{Binding Path=Name}"
                            CornerRadius="5"
                            Width="50"
                            Height="50"/>
                    <StackPanel Orientation="Vertical" Margin="5">
                        <TextBlock Text="{Binding Path=Name}" Margin="5"/>
                        <TextBlock Text="{Binding Path=Name,Converter={StaticResource conv}}" Margin="2"/>
                    </StackPanel>
                </StackPanel>
            </DataTemplate>
            
            <Style x:Key="ItemStyle" TargetType="ListBoxItem">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="ListBoxItem">
                            <Border CornerRadius="2" 
                                    Margin="3"
                                    BorderBrush="Gray"
                                    BorderThickness="2">
                                <ContentPresenter Margin="2"/>
                            </Border>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            
        </Grid.Resources>

        <ListBox ItemTemplate="{StaticResource BoxTemplate}"
                 ItemContainerStyle="{StaticResource ItemStyle}"
                 Name="listColors" Margin="20">
        </ListBox>
    </Grid>

Perfect!

[Edit:
I would like to add one more feature in this application. Its like adding a TextBox on top of ListBox to filter the Colors. For example, if you want to find a particular color, just type in it and it will return the results.

For this we will use the Text_Changed event of the TextBox and in it use the Filter property of the ICollectionView to filter the results.

This is the code-behind :


       private ICollectionView view;

       //Add this Loaded event of the Window
      view = CollectionViewSource.GetDefaultView(listColors.ItemsSource);

        void txtName_TextChanged(object sender, TextChangedEventArgs e)
        {
            view.Filter = delegate(object item)
            {
                PropertyInfo info = item as PropertyInfo;
                return info.Name.ToLower().StartsWith(txtName.Text.ToLower());
            };
        }

Here is how it will look like :

With Filter

With Filter

Happy coding! 🙂

Advertisements

March 25, 2011 - Posted by | WPF

1 Comment »

  1. thank you – quick and easy to deploy 🙂

    Comment by Braden | February 25, 2013 | Reply


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: