Click here to Skip to main content
15,860,972 members
Articles / Desktop Programming / WPF

Color Picker using WPF Combobox

Rate me:
Please Sign up or sign in to vote.
4.81/5 (14 votes)
29 Dec 2010CPOL1 min read 95.4K   3.8K   16   18
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:

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

The namespace used for this is:

C#
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.

C#
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:

XML
  <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:

C#
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:

XML
 <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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) NeST
India India
Professional: Have 5 years experience in ASP.Net,C#.Net,MVC,WPF,,Entity Framework,WCF,LINQ,JQuery,JQuery Mobile,MS SQL,Oracle,Silverlight,MS CRM,Dynamics GP

Academics : BTech in Computer Science and Engineering from Mar Athanasius College of Engineering,Kothamangalam,Kerala .

Location : Kothamangalam, Ernakulam ,Kerala ,India
Presently working at Technopark Trivandrum,
Mob: 8281065563

Comments and Discussions

 
QuestionDisplay Name along with color Pin
codestar0072-Oct-13 21:55
professionalcodestar0072-Oct-13 21:55 
GeneralMy vote of 1 Pin
Yves Goergen15-Sep-12 2:36
Yves Goergen15-Sep-12 2:36 
GeneralBrush picker Pin
Michael Bookatz13-Jun-11 7:02
Michael Bookatz13-Jun-11 7:02 
GeneralRe: Brush picker Pin
sudheer muhammed26-Jun-11 18:00
sudheer muhammed26-Jun-11 18:00 
QuestionHow can I set a selected color? Pin
Matthias1-Jan-11 0:04
Matthias1-Jan-11 0:04 
AnswerRe: How can I set a selected color? Pin
sudheer muhammed3-Jan-11 17:47
sudheer muhammed3-Jan-11 17:47 
GeneralRe: How can I set a selected color? [modified] Pin
Matthias3-Jan-11 23:06
Matthias3-Jan-11 23:06 
GeneralRe: How can I set a selected color? Pin
brouwer7-Jan-11 3:54
brouwer7-Jan-11 3:54 
GeneralRe: How can I set a selected color? Pin
Sacha Barber20-Apr-11 0:18
Sacha Barber20-Apr-11 0:18 
GeneralRe: How can I set a selected color? Pin
ricardosobrado27-Jun-12 5:17
ricardosobrado27-Jun-12 5:17 
GeneralRe: How can I set a selected color? Pin
Sacha Barber27-Jun-12 6:26
Sacha Barber27-Jun-12 6:26 
GeneralRe: How can I set a selected color? Pin
ricardosobrado28-Jun-12 1:21
ricardosobrado28-Jun-12 1:21 
GeneralRe: How can I set a selected color? [modified] Pin
largesys16-Dec-13 18:20
largesys16-Dec-13 18:20 
GeneralMy vote of 5 Pin
Hiren solanki31-Dec-10 3:01
Hiren solanki31-Dec-10 3:01 
It's very good short,sweet and neat article.

Keep up your good work with CP.
GeneralMy vote of 5 Pin
RaviRanjanKr31-Dec-10 2:56
professionalRaviRanjanKr31-Dec-10 2:56 
GeneralMy vote of 5 Pin
Venkatesh Mookkan30-Dec-10 17:07
Venkatesh Mookkan30-Dec-10 17:07 
Generaluseful Pin
BillW3330-Dec-10 4:47
professionalBillW3330-Dec-10 4:47 
GeneralMy vote of 5 Pin
prasad0230-Dec-10 1:10
prasad0230-Dec-10 1:10 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.