WPF ListBox of Colors


This entry is part 5 of 6 in the series WPF ListBox

This post is a sample Windows Presentation Foundation (WPF) program of a ListBox that lists all of the 256 predefined colors. The 256 named colors are based on the X11 color names from the Cascading Style Sheets, Level 3 (CSS3) specification. The user can pick a color from the list and set the background, similar to how they might do to set preferences. This is based on some code in an article List colors in WPF and C# at C# Helper. The great thing about this approach is that we don’t need to manually add all these colors. We use Reflection to get the list and load the list upon the Window_Loaded event. Notice that we have Loaded=”Window_Loaded” in the XAML. We have a very similar post that uses a ComboBox instead of a ListBox. We also have a post that adds SQLite to the ComboBox project that’s called WPF ComboBox Colors with SQLite.

There are two more posts here that also show a list of colors. The first one uses a combo box instead of a list. The second one takes the combo box example a step or two further and brings in a SQLite database to save the user’s color choice.

Below is a screenshot of how the program looks after the user has chosen Coral.

WPF ListBox of Colors

Below is the XAML code. The most interesting part of the XAML code below is the DataTemplate. The ListBox has an ItemTemplate. Under that we have a DataTemplate. The DataTemplate can hold a single child, which in this example is a StackPanel. The StackPanel’ Orientation is Horizontal and it has three objects inside it. The controls use bindings to set some of their properties equal to values that will be provided by the data objects bound to the ListBox. So where are the SampleBrush, ColorName, and HexValue properties defined? The program stores color information in the ColorInfo class, shown at the bottom.

<Window x:Class="ListColorsInWPF.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ListColorsInWPF"
        mc:Ignorable="d"
        Title="ListColorsInWPF" Height="450" Width="450"
        Loaded="Window_Loaded">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="20"/>
            <RowDefinition Height="20"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TextBlock Name="txtblkTitle" Grid.Row="0"></TextBlock>
        <TextBlock Name="txtblkRGBNumbers" Grid.Row="1"></TextBlock>

        <ListBox Grid.Row="2" Name="lstboxColors" ScrollViewer.CanContentScroll="True" 
                 ScrollViewer.VerticalScrollBarVisibility="Auto" 
                 SelectionChanged="lstboxColors_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" Margin="0,3,0,0">
                        <StackPanel.Resources>
                            <Style TargetType="TextBlock">
                                <Setter Property="Margin" Value="5,0,0,0"/>
                            </Style>
                        </StackPanel.Resources>
                        <Rectangle Width="30" Fill="{Binding SampleBrush}"/>
                        <TextBlock Name="ColorOfItem" Width="130" Text="{Binding ColorName}"/>
                        <TextBlock Width="70" Text="{Binding HexValue}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

Here is the code behind. To attach data to the ListBox, we use the ItemsSource property. The LINQ query is also another interesting feature of this example.

using System.Linq;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace ListColorsInWPF
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        // List samples of the named colors.
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            var color_query = from PropertyInfo property in typeof(Colors).GetProperties()
                              orderby property.Name
                              //orderby ((Color)property.GetValue(null, null)).ToString()
                              select new ColorInfo(
                                      property.Name,
                                      (Color)property.GetValue(null, null));
            lstboxColors.ItemsSource = color_query;
        }
        private void lstboxColors_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ListBox lb = sender as ListBox;
            //foreach (object o in lb.SelectedItems)
            //    MessageBox.Show((o as ColorInfo).ColorName +
            //        "\nHex Value " + (o as ColorInfo).HexValue +
            //        "\nRed " + (o as ColorInfo).Color.R + 
            //        "\nGreen " + (o as ColorInfo).Color.G + 
            //        "\nBlue " + (o as ColorInfo).Color.B +
            //        "\nAlpha " + (o as ColorInfo).Color.A);

            // change the background of the title in the first TextBox
            txtblkTitle.Background = new SolidColorBrush(Color.FromRgb((lb.SelectedItem as ColorInfo).Color.R, 
                (lb.SelectedItem as ColorInfo).Color.G, (lb.SelectedItem as ColorInfo).Color.B));

            // display the RBG and A of the selected color
            object ci = lb.SelectedItem;
            txtblkRGBNumbers.Text = (lb.SelectedItem as ColorInfo).ColorName +
                    " is Red " + (ci as ColorInfo).Color.R +
                    "     Green " + (ci as ColorInfo).Color.G +
                    "     Blue " + (ci as ColorInfo).Color.B +
                    "     Alpha " + (ci as ColorInfo).Color.A;
        }
    }
    // Used to display color name, RGB value, and sample.
    // From C Sharp Helper:
    // http://csharphelper.com/blog/2015/10/list-colors-in-wpf-and-c/
    //
    public class ColorInfo
    {
        public string ColorName { get; set; }
        public Color Color { get; set; }
        public SolidColorBrush SampleBrush
        {
            get { return new SolidColorBrush(Color); }
        }
        public string HexValue
        {
            get { return Color.ToString(); }
        }
        public ColorInfo(string color_name, Color color)
        {
            ColorName = color_name;
            Color = color;
        }
    }
}
Series Navigation<< WPF ListBox ControlWPF ListBox List Fonts >>

Leave a Reply