Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Color Picker using WPF Combobox

0.00/5 (No votes)
30 Dec 2010 11  
The article will demonstrate how to use a combobox as a colorpicker tool just like we have in Visual Studio color picker tool.

Introduction

In Visual Studio and other tools, we found that whenever we need to select a color for a particular element, a color combobox is being used. This article will guide you to make a combo box which binds all the system colors.

colorcombo_preview.jpg

Background

The reader is assumed to be at least a beginner in WPF who knows the basics of data binding techniques, dependency properties, etc.

Using the Code

The collection of colors are extracted from the extension:

 <sys:String>System.Windows.Media.Colors, PresentationCore,
            Version=3.0.0.0, Culture=neutral, 
            PublicKeyToken=31bf3856ad364e35</sys:String> 

The namespace used for this is:

xmlns:sys="clr-namespace:System;assembly=mscorlib" 

The extracted colors are binded to an ObjectDataProvider which serves as the datasource for the combobox. The combobox item template is divided into two sections, one for displaying the color and another for displaying name of color. Textblock is used for both and the name of color is binded to one of textblocks' text property and background of the others. The selectedvalue is binded to a dependency property "SelectedColor" of type Brush.

   public Brush SelectedColor
        {
            get { return (Brush)GetValue(SelectedColorProperty); }
            set { SetValue(SelectedColorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedColor.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedColorProperty =
            DependencyProperty.Register("SelectedColor", typeof(Brush), 
		typeof(Colorpicker), new UIPropertyMetadata(null)); 

The source code contains two XAML files and CS files for the colorcombo usercontrol and a window file which manipulates this usercontrol.

The Colorpicker.xaml is a WPF usercontrol and the XAML will look like:

  <UserControl x:Class="Customcontrols.Colorpicker"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:sys="clr-namespace:System;assembly=mscorlib" 
		Height="40" Width="200" Name="uccolorpicker"
             mc:Ignorable="d">
    <UserControl.Resources>
        <ResourceDictionary>
            <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>

        </ResourceDictionary>
    </UserControl.Resources>
    <Grid>
        <ComboBox Name="superCombo" 
    ItemsSource="{Binding Source={StaticResource colorPropertiesOdp}}" 
	SelectedValuePath="Name"  SelectedValue="{Binding ElementName=uccolorpicker, 
	Path=SelectedColor}">
        <ComboBox.ItemTemplate>
            <DataTemplate>
                  <StackPanel Orientation="Horizontal">
                        <TextBlock Width="20" Height="20" Margin="5" 
			Background="{Binding Name}"/>
                        <TextBlock  Text="{Binding Name}"/>
                    </StackPanel>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        </ComboBox>
    </Grid>
</UserControl>

The Colorpicker.cs is the associated CS file for the colorpicker usercontrol. In that, we create a dependency property "SelectedColor" for setting the selected color. The CS file will look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace Customcontrols
{
    /// <summary>
    /// Interaction logic for Colorpicker.xaml
    /// </summary>
    public partial class Colorpicker : UserControl
    {
        public Colorpicker()
        {
            InitializeComponent();
        }

        public Brush SelectedColor
        {
            get { return (Brush)GetValue(SelectedColorProperty); }
            set { SetValue(SelectedColorProperty, value); }
        }

        // Using a DependencyProperty as the backing store for SelectedColor.  
        // This enables animation, styling, binding, etc...
        public static readonly DependencyProperty SelectedColorProperty =
            DependencyProperty.Register("SelectedColor", 
		typeof(Brush), typeof(Colorpicker), new UIPropertyMetadata(null));
    }
}	

The mainwindow.xaml is a WPF window which uses the colorpicker usercontrol and displays the color which control selects and the XAML will look like:

 <Window x:Class="Customcontrols.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="300" Width="600" Name="cc"
        xmlns:local="clr-namespace:Customcontrols">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition></RowDefinition>
            <RowDefinition></RowDefinition>
        </Grid.RowDefinitions>
        <local:Colorpicker  x:Name="superCombo" Grid.Row="0"></local:Colorpicker>
        <StackPanel Grid.Row="1"  Orientation="Horizontal">
            <TextBlock FontWeight="ExtraBlack"  
		Text="You selected" Height="20" Width="91">
	   </TextBlock>
            <TextBlock Width="100" Height="100" 
		Background="{Binding ElementName=superCombo, Path=SelectedColor}" >
	   </TextBlock>
        </StackPanel>        
    </Grid>
</Window>		

Hope you understand the code, download the project and check it out.

History

  • 30th December, 2010: Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here