Click here to Skip to main content
15,893,814 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 96.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

 
GeneralMy vote of 1 Pin
Yves Goergen15-Sep-12 2:36
Yves Goergen15-Sep-12 2:36 

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.