Posted by: Zeeshan Amjad | September 2, 2009

Data binding of Combo Box in WPF

Data binding of Combo box is very much similar to List Box. In the simplest form we just have to create one array of string and assign it to the ItemsSource property of combo box. Combo box will do the rest of the work. Here is a simple application to demonstrate this.

Here is a XAML code to display one combo box inside the window.

  1: <Window x:Class="wpfComboBox.Window1"
  2:     xmlns=""
  3:     xmlns:x=""
  4:     Title="Combo Box Demo" Height="300" Width="400" Loaded="Window_Loaded">
  5:     <Grid>
  6:         <ComboBox Name="cmbCombo" Margin="5" 
  7:                   VerticalAlignment="Center" HorizontalContentAlignment="Stretch">
  9:         </ComboBox>
 10:     </Grid>
 11: </Window>

Now if we want to display the name of all the colors defined in the .Net namespace then we can do it very easily. First we will get the array of string and then assign it to the combo box. Here is the simple code to show this.

  1: string[] colors = System.Enum.GetNames(typeof(KnownColor));
  2: cmbCombo.ItemsSource = colors;

Here is a code of complete C# application.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Windows;
  4: using System.Windows.Controls;
  5: using System.Drawing;
  7: namespace wpfComboBox
  8: {
  9:     /// <summary>
 10:     /// Interaction logic for Window1.xaml
 11:     /// </summary>
 12:     public partial class Window1 : Window
 13:     {
 14:         public Window1()
 15:         {
 16:             InitializeComponent();
 17:         }
 19:         private void Window_Loaded(object sender, RoutedEventArgs e)
 20:         {
 21:             string[] colors = System.Enum.GetNames(typeof(KnownColor));
 23:             cmbCombo.ItemsSource = colors;
 24:         }
 25:     }
 26: }

Here is the output of this program.



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: