Creating a ListBox that Shows All Predefined WPF Colors

In WPF, you can use the Colors class to access a series of predefined colors, defined as static properties of the Colors class.  You reference each color just using the name of the color.

For reference, here’s a little application that shows all colors in a ListBox.  (Credit to casperOne, in a stackoverflow post that shows how to create an object that encapsulates the list of properties in the Colors class).

Here’s the final result.  (Click on the image to see it full-sized).

The XAML for generating this list is pretty straightforward:

<Window
	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" mc:Ignorable="d"
	xmlns:local="clr-namespace:WpfApplication1"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    x:Class="WpfApplication1.MainWindow"
	x:Name="Window"
	Title="All Colors"
	Width="640" Height="480" >

    <Window.Resources>
        <ObjectDataProvider MethodName="GetType"
        ObjectType="{x:Type sys:Type}" x:Key="colorsTypeOdp">
            <ObjectDataProvider.MethodParameters>
                <sys:String>System.Windows.Media.Colors, PresentationCore,
                Version=3.0.0.0, Culture=neutral,
                PublicKeyToken=31bf3856ad364e35</sys:String>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

        <ObjectDataProvider ObjectInstance="{StaticResource colorsTypeOdp}"
        MethodName="GetProperties" x:Key="colorPropertiesOdp">
        </ObjectDataProvider>
    </Window.Resources>

    <ListBox ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}"
		ScrollViewer.HorizontalScrollBarVisibility="Disabled"
		ScrollViewer.VerticalScrollBarVisibility="Auto" >
    	<ListBox.ItemsPanel>
    		<ItemsPanelTemplate>
    			<WrapPanel />
			</ItemsPanelTemplate>
		</ListBox.ItemsPanel>
		<ListBox.ItemTemplate>
        <DataTemplate>
        	<StackPanel Orientation="Vertical">
                <Rectangle Fill="{Binding Path=Name}" Stroke="Black" Margin="4" StrokeThickness="1" Height="50" Width="81"/>
                <Label Content="{Binding Path=Name}" />
			</StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
    </ListBox>
</Window>
Advertisement

One thought on “Creating a ListBox that Shows All Predefined WPF Colors

  1. Pingback: c# - Comment puis-je afficher les couleurs en WPF XAML?

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 )

Facebook photo

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

Connecting to %s