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

Color Picker using WPF Combobox

By , 29 Dec 2010
 

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)

About the Author

sudheer muhammed
Software Developer
India India
Member
Professional: Have 2 years experience in ASP.Net,AJAX,C#.Net,
LINQ,MVC,JQuery,JQuery Mobile,MS SQL,Oracle
Beginner in WPF ,Entity Framework,WCF,Silverlight,MVC 3,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

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 1memberName taken15 Sep '12 - 2:36 
GeneralBrush pickermemberMichael Bookatz13 Jun '11 - 7:02 
GeneralRe: Brush pickermembersudheer muhammed26 Jun '11 - 18:00 
QuestionHow can I set a selected color?memberMatthias1 Jan '11 - 0:04 
First I tried to bind the SelectedColor via data binding to my viewmodel, but it did'nt work, so I tried
<local:Colorpicker SelectedColor="Aquamarine"/>
to see, if I can set an initial value, but it didn't work. So how can I set a SelectedColor ?
 
Thanks,
Matthias
AnswerRe: How can I set a selected color?membersudheer muhammed3 Jan '11 - 17:47 
GeneralRe: How can I set a selected color? [modified]memberMatthias3 Jan '11 - 23:06 
GeneralRe: How can I set a selected color?memberbrouwer7 Jan '11 - 3:54 
GeneralRe: How can I set a selected color?mvpSacha Barber20 Apr '11 - 0:18 
GeneralRe: How can I set a selected color?memberricardosobrado27 Jun '12 - 5:17 
GeneralRe: How can I set a selected color?mvpSacha Barber27 Jun '12 - 6:26 
GeneralRe: How can I set a selected color?memberricardosobrado28 Jun '12 - 1:21 
GeneralMy vote of 5memberHiren Solanki31 Dec '10 - 3:01 
GeneralMy vote of 5memberRaviRanjankr31 Dec '10 - 2:56 
GeneralMy vote of 5memberVenkatesh Mookkan30 Dec '10 - 17:07 
GeneralusefulmemberCIDev30 Dec '10 - 4:47 
GeneralMy vote of 5memberprasad0230 Dec '10 - 1:10 

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

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