Search code examples
c#wpfcollectionviewsource

Correct Way to bind ComboBox to CollectionViewSource


Hey i have a CollectionViewSource Property on my ViewModel.

This ViewModel is bound to a ComboBox this way:

<ComboBox   ItemsSource="{Binding Products.View}" 
SelectedItem="{Binding SelectedEntity.Product}"  
IsSynchronizedWithCurrentItem="True"/>

When binding to an existing SelectedEntity it works fine.

When i try to bind to an SelectedEntity, that dosn't posses a Product i want to display the first Item from the List. Therefore i tried to use Products.View.MoveCurrentToFirst(), but still the first item isn't displayed.

It of course works when i set SelectedEntity.Product = Products.View.CurrentItem.

What can i do, to improve my code? This looks somewhat wrong to me...


Solution

  • SelectedItem in WPF selects the entire instance, so if you're binding SelectedItem to an Entity's navigation property, then all is good. However, if you're binding SelectedItem to an Entity's non-navigation property, then this can be a problem, and I'd recommend if this this a business requirement that you instead bind SelectedValue.

    For me, I find it best to bind SelectedItem to my Entity's navigation property AND SelectedValue to my Entity's value property.

    I hope this helps.