how do I set selectedvalue and itemssource of combobox within datatemplate

244 views Asked by At

This question is related to MVVM project structure.

For displaying data in a ListView I use a DataTemplate. The ItemsSource for the ListView is an ObservableCollection(of Person). Nothing special so far.

But in the DataTemplate I want to display a the State property of each Person in a ComboBox, where the actual value is displayed, and the user can choose another State. The State comes from States, that is an ObservableCollection(of State).

In order to show all the States, I need to Bind the DataContext to the "toplevel" of the ViewModel. But how do I come down to the individual person again, that is shown in the DataTemplate? Or do I need another approach for this problem?

In XAML I have this:

    <ComboBox DataContext="{Binding DataContext, ElementName=pageRoot}" ItemsSource="{Binding States}" DisplayMemberPath="Description" SelectedValue="{Binding ??????}"  SelectedValuePath="ID" />

My question is: what do I need to set in order to Bind the SelectedValue correctly so that it shows the actual State per Person in the text-field of the Combobox?

1

There are 1 answers

0
Peter Klein On

Got it! For the ItemsSource of the ComboBox I need the "higher" level of the DataContext hierarchy. Instead of Binding the entire ComboBox to that DataContext, I only needed to Bind the ItemsSource to that level.

The corrected code now looks like so:

<ComboBox                     
                ItemsSource="{Binding DataContext.States, ElementName=pageRoot}" 
                DisplayMemberPath="Description" 
                SelectedValue="{Binding State.ID, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" 
                SelectedValuePath="ID" 

Trial and error works out! :-)