How to make simple combobox with selected value in XAML?
Asked Answered
M

4

10

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>
Mohur answered 30/11, 2009 at 9:28 Comment(0)
S
19

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>
Sulphone answered 30/11, 2009 at 10:6 Comment(2)
ComboBoxItem doesn't have a "Value" property.Mame
oh I'm sorry, should be Tag, not value, was a mistake by meSulphone
V
5
<ComboBox SelectedValuePath="Content" SelectedValue="{Binding Source="...", Path="..."}">
   <ComboBoxItem Content="..." isSelected="true"/>
   <ComboBoxItem Content="..." />
   <ComboBoxItem Content="..." />
</ComboBox>

It should work with content, tag... or any other property you'd like to bind.

Verst answered 3/8, 2014 at 12:59 Comment(0)
W
2
<StackPanel>
    <ComboBox AllowDrop="True">
        <ComboBoxItem Tag="CO">Colorado</ComboBoxItem>
        <ComboBoxItem Tag="CA" IsSelected="True">California</ComboBoxItem>
        <ComboBoxItem Tag="NM">New Mexico</ComboBoxItem>
    </ComboBox>
</StackPanel>

You need to set AllowDrop="True" for the combobox and isselected for the item.

Wickham answered 26/11, 2014 at 3:43 Comment(0)
P
1

The ComboBox element has a SelectedItem property, maybe this is the one you need.

Platino answered 30/11, 2009 at 10:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.