views:

388

answers:

1

Hi,

How to set the combobox selected item in xaml? I tried something doing like this

<ComboBox x:Name="cmbProject"
    ItemsSource="{Binding  Project}"
    DisplayMemberPath="Name"
    SelectedValuePath="Id"
    SelectedItem="{Binding Path=Project,Mode=TwoWay}"
    SelectedValue="{Binding Path=Id,Mode=OneWay}"/>

The above code does not work. I don't know where i am going wrong.

Please help

Thanks Sharath

A: 

The ItemsSource property should be a Collection, i.e. Projects or ProjectList, I guess... Also, you only need to set the DisplayMemberPath and the SelectedValue:

 <ComboBox x:Name="cmbProject" ItemsSource="{Binding Projects}"
           DisplayMemberPath="Name"
           SelectedValue="{Binding Project, Mode=TwoWay}" />

Update: based on the info in the comments the code becomes:

<ComboBox x:Name="cmbProjectStatus"
          ItemsSource="{Binding ProjectStatuses}"
          DisplayMemberPath="Name"
          SelectedValuePath="ID"
          SelectedValue="{Binding Path=ProjectStatus.ID}"
          SelectedItem="{Binding Path=ProjectStatus}" />

The DataContext has a ProjectStatus property of type ProjectStatus and a ProjectStatuses property of type ObservableCollection<ProjectStatus>.

Julien Poulin
I tried it, But still it is not showing the selected item in the combobox.
It worked for me when I tried, how do you set the selected item? Can you post the code?
Julien Poulin
<ComboBox x:Name="cmbProjectStatus" ItemsSource="{Binding ProjectStatuses}" DisplayMemberPath="Name" SelectedValuePath="Id"SelectedItem="{Binding Path=ProjectStatus,Mode=TwoWay}" SelectedValue="{Binding Path=StatusId,Mode=OneWay}>