Select Page
This entry has been published on 2013-10-09 and may be out of date.

Last Updated on 2013-10-09.

For WPF beginners coming from Windows Forms, it may seem like it’s easier to use a ComboBox with the drop-down items loaded from an external database / Entity Framework than to work with simple static items.
For DB access, you set ItemsSource (e.g. EF object), DisplayMemberPath (the column name for the text output), SelectedValuePath (e.g. the ID column) and this should be all.

With a list of simple, static drop-down items, which can e.g. created by designer or in the XAML code, it can be a bit tricky though.

The following XAML example shows how to use static ComboBoxItems and bind the selected value to an EF object row, e.g. an order position.

First, set a DataContext property, e.g. an EF object, where you want to save the selected value.

this.DataContext = myEFdb.position.First(); //or use a LINQ select etc.

Place a ComboBox in your WPF Page or Window and add some ComboBoxItems via the Items property, e.g. in designer.

Set the SelectedValue property to the DataContext column of your choice.

Important: You need to set a Tag attribute per ComboBoxItem and also set SelectedValuePath to “Tag”. Do not use DisplayMemberPath her! At least in my case it did not work otherwise; the binding would not really work (blank combo, or item does not get accepted, or not saved, not loaded, etc.)

So a simple working code could look like this:

<ComboBox SelectedValue="{Binding myEFcolumn}" SelectedValuePath="Tag">
    <ComboBoxItem Content="foo" Tag="foo"/>
    <ComboBoxItem Content="bar" Tag="bar"/>
</ComboBox>