How to make simple combobox with selected value in XAML?

Edward Tanguay picture Edward Tanguay · Nov 30, 2009 · Viewed 34.9k times · Source

What is the correct syntax to select a combobox item with value (not index) in pure XAML?

Doesn't work:

<StackPanel>
    <ComboBox SelectedValue="CA">
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

Doesn't work:

<StackPanel>
    <ComboBox SelectedValue="CA">
        <ComboBoxItem Value="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Value="CA">California</ComboBoxItem>
        <ComboBoxItem Value="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

Even this doesn't work:

<ComboBox SelectedValue="Colorado">
    <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
    <ComboBoxItem Tag="CA">California</ComboBoxItem>
    <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
</ComboBox>

This doesn't work:

<StackPanel>
    <ComboBox SelectedItem="CA">
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

Answer

martin picture martin · Nov 30, 2009

I think this should work. Have a try.

<StackPanel>
    <ComboBox>
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA" IsSelected="True">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>