Click here to Skip to main content
Click here to Skip to main content

Color Picker using WPF Combobox

, 30 Dec 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

sudheer muhammed
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 Pinprofessionalcodestar0072-Oct-13 22:55 
GeneralMy vote of 1 PinmemberName taken15-Sep-12 3:36 
Does not select an initial color and does not give back a user selection. It's entirely useless.
GeneralBrush picker PinmemberMichael Bookatz13-Jun-11 8:02 
GeneralRe: Brush picker Pinmembersudheer muhammed26-Jun-11 19:00 
QuestionHow can I set a selected color? PinmemberMatthias1-Jan-11 1:04 
AnswerRe: How can I set a selected color? Pinmembersudheer muhammed3-Jan-11 18:47 
GeneralRe: How can I set a selected color? [modified] PinmemberMatthias4-Jan-11 0:06 
GeneralRe: How can I set a selected color? Pinmemberbrouwer7-Jan-11 4:54 
GeneralRe: How can I set a selected color? PinmvpSacha Barber20-Apr-11 1:18 
GeneralRe: How can I set a selected color? Pinmemberricardosobrado27-Jun-12 6:17 
GeneralRe: How can I set a selected color? PinmvpSacha Barber27-Jun-12 7:26 
GeneralRe: How can I set a selected color? Pinmemberricardosobrado28-Jun-12 2:21 
GeneralRe: How can I set a selected color? [modified] Pinmemberlargesys16-Dec-13 19:20 
GeneralMy vote of 5 PinmemberHiren Solanki31-Dec-10 4:01 
GeneralMy vote of 5 PinmemberRaviRanjankr31-Dec-10 3:56 
GeneralMy vote of 5 PinmemberVenkatesh Mookkan30-Dec-10 18:07 
Generaluseful PinmemberCIDev30-Dec-10 5:47 
GeneralMy vote of 5 Pinmemberprasad0230-Dec-10 2:10 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141223.1 | Last Updated 30 Dec 2010
Article Copyright 2010 by sudheer muhammed
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid