Live Chat Icon For mobile
Live Chat Icon

WPF FAQ - ComboBox

Find answers for the most frequently asked questions
Expand All Collapse All

ComboBox can be bound to an enum in XAML or in code. The below code shows binding to the ‘Visibility’ enum,


<ObjectDataProvider x:Key='VisibilityList' ObjectType='{x:Type sys:Enum}' MethodName='GetValues'>
		<x:TypeExtension TypeName='sys:Visibility'>

<ComboBox x:Name='ComboBox1' ItemsSource='{Binding Source={StaticResource VisibilityList}}' SelectedIndex='0' />

Same thing in code-behind:


// Setup the binding as follows:
comboBox1.ItemsSource = Enum.GetValues(typeof Visibility);

You can retrieve the selected enum value at any time using a simple cast as follows:

Visibility visibility = (Visibility)this.myCombo.SelectedItem;

One reason your binding to the SelectedValue may not work is if you have manually added ComboBoxItems as follows:

<ComboBox Name='mycombo' SelectedValue='{Binding Path=operator, Mode=TwoWay}' Width = '50'>   
	<ComboBoxItem Content=''></ComboBoxItem>  

Instead, set the ItemsSource property to a list of strings as follows and the SelectedValue data binding will work fine:

        <src:MyList x:Name='myList' x:Key='myList'></src:MyList>  
<ComboBox Name='mycombo' SelectedValue='{Binding Path=Code, Mode=TwoWay}'    
                  ItemsSource='{StaticResource myList}' Width = '50' Height='30' >  

Code Behind:

    public class MyList : List   
        public MyList()    

The ComboBox, like the other ItemsControl can be bound to any IList, ObservableCollection or ObjectDataProvider (containing a list type data) as explained in this MSDN topic:

ItemsControl Content Model Overview

If bound to an ObservableCollection, changes happening in the collection will automatically reflect in the ComboBox.

You can also bind to XML Data using an XMLDataProvider as explained in this topic:

How to: Bind to XML Data Using an XMLDataProvider and XPath Queries

Bind the ComboBox to a CollectionViewSource to be able to bind to sorted or grouped views of your list.

CollectionViewSource Class

You can also bind to a DataTable in an ADO.NET DataSet as follows:

How to: Bind to an ADO.NET Data Source


Unfortunately, the first version of WPF does not provide a TextChanged event for a ComboBox like the one available for a TextBox. So, a workaround like the following is required:


public Window1()
    this.comboBox.Loaded += delegate
        TextBox editTextBox = comboBox.Template.FindName('PART_EditableTextBox', comboBox) as TextBox;
        if (editTextBox != null)
            editTextBox.TextChanged += delegate { MessageBox.Show(comboBox.Text); };


Share with

Couldn't find the FAQs you're looking for?

Please submit your question and answer.