DeeStackOverflow
DeeStackOverflow

Reputation: 2781

Problem setting selectedvalue for combobox in xaml

Here is a snippet of my xaml:

    <ComboBox x:Name="cbo1" Width="100" SelectedValue="200">
        <ComboBoxItem Name="n1">100</ComboBoxItem>
        <ComboBoxItem Name="n2">200</ComboBoxItem>
    </ComboBox>

Why doesn't this work ? The '200' is not selected when I run it. Ideally, I am trying to do SelectedValue="{Binding MyValue}".

Upvotes: 3

Views: 1404

Answers (2)

fixagon
fixagon

Reputation: 5566

The selected value in this case is from type ComboBoxItem and not integer or string as you wished.

so what can you do against that? there exists a property for the combobox which defines which property of the selected object should be used as value and which as DisplayMember (the visualization)

in your case you have to set the SelectedValuePath to "Content". (The 200 are in your case the content of the ComboBoxItem)

example:

<ComboBox x:Name="cbo1" Width="100" SelectedValue="200" SelectedValuePath="Content">
    <ComboBoxItem Name="n1">100</ComboBoxItem>
    <ComboBoxItem Name="n2">200</ComboBoxItem>
</ComboBox>

Upvotes: 4

RQDQ
RQDQ

Reputation: 15569

 <ComboBox x:Name="cbo1" Width="100" >
       <ComboBoxItem Name="n1">100</ComboBoxItem>
       <ComboBoxItem Name="n2" IsSelected="True">200</ComboBoxItem>
 </ComboBox>

Upvotes: 0

Related Questions