Developing in XAML (Windows 8, Silverlight, Windows Phone, or WPF) gives you a powerful combination of declarative markup with databinding, but one shortcoming I often come up against is the ability to build simple ComboBox elements declaratively with both Content and Values.
If you are familiar with HTML, you know that you can use a
select tag to pair the display name with a key value, such as:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Notice that the value for each item does not have to exactly match the display name (in the example above, there is no capitalization in the value).
With XAML, you have two options for ComboBox items: either bind the ItemsSource to a collection which gives you the ability to bind the DisplayMemberPath and SelectedValuePath to different properties on your object, or you can declare ComboBoxItems in XAML. But the declarative ComboBoxItem only has a Content property which is used as the display property so you can't set different display and key values.
However, using the Tag property that is built into every control, we can use control binding to display the Content property and use the Tag property as our key. Here is a Windows 8 application that lists cardinal directions in the ComboBox, but the underlying value of each direction is the compass heading in degrees:
<ComboBox SelectedValue="{Binding SelectedDirection, Mode=TwoWay}" SelectedValuePath="Tag">
<ComboBoxItem Content="North" Tag="0"/>
<ComboBoxItem Content="East" Tag="90"/>
<ComboBoxItem Content="South" Tag="180"/>
<ComboBoxItem Content="West" Tag="270"/>
</ComboBox>
The key to this is setting the SelectedValuePath to "Tag." This gives us a quick way to declare our ComboBoxItems in XAML and still bind the value to something other than the display value.
In my application, I bind the SelectedValue to a property in my ViewModel and display the value below the ComboBox which automatically updates when the direction is changed in the ComboBox:
Get the source on GitHub