WPF combobox value and display text

Viewed 105871

I'm used to doing things like

State.Items.Add(new ListItem { Text = "SomeState", Value = NumericIDofState });

Where State is a Listbox in ASP.NET.

How do i achieve the same with a WPF ComboBox? I do see a property called 'Content' in the ComboBoxItem object but how do i assign each item a value other than what's displayed to the user? Please help.

4 Answers

If you only want to expose a simple property in the viewmodel and handle the text for the choices in the view you can do a simple solution like this:

    <ComboBox SelectedValuePath="Tag" SelectedValue="{Binding YourIntProperty, Mode=TwoWay}">
        <ComboBoxItem Content="First choice" Tag="0"/>
        <ComboBoxItem Content="Second choice" Tag="1"/>
        <ComboBoxItem Content="Third choice" Tag="2"/>
    </ComboBox>

Example with a bool property:

    <ComboBox SelectedValuePath="Tag" SelectedValue="{Binding IsActive, Mode=TwoWay}">
        <ComboBoxItem Content="No" Tag="False"/>
        <ComboBoxItem Content="Yes" Tag="True"/>
    </ComboBox>

Type-verbose alternatives (original examples)

Below are more verbose alternatives where the types are explicitly declared. Depending on your preferred style (or maybe some types that requires it), maybe it suits you better.

<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding YourIntProperty, Mode=TwoWay}">
    <ComboBoxItem Content="First choice">
        <ComboBoxItem.Tag>
            <sys:Int32>0</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Second choice">
        <ComboBoxItem.Tag>
            <sys:Int32>1</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Third choice">
        <ComboBoxItem.Tag>
            <sys:Int32>2</sys:Int32>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

Example with a bool property:

<ComboBox SelectedValuePath="Tag" SelectedValue="{Binding IsActive, Mode=TwoWay}">
    <ComboBoxItem Content="No">
        <ComboBoxItem.Tag>
            <sys:Boolean>False</sys:Boolean>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
    <ComboBoxItem Content="Yes">
        <ComboBoxItem.Tag>
            <sys:Boolean>True</sys:Boolean>
        </ComboBoxItem.Tag>
    </ComboBoxItem>
</ComboBox>

The sys namespace is declared as this:

xmlns:sys="clr-namespace:System;assembly=mscorlib"
Related