I have a ComboBox which content might change. The issue is when the content is changed, 1) i lose the previous selectedIndex, and 2) SelectedIndex is set to -1.
I would like an MVVM solution, not some solution involving code-behind.
I can have the SelectedIndex set to 0 on content change, but -1 is not a valid value for my model.
What i did as a ‘trick’ was to have the setter of the property bound to SelectedIndex to set the value to 0 when the value is set to -1. So now i don’t have incorrect value in my model. But the ComboBox does not display the “0”th item, rather an empty box.
What could i do to have my ComboBox display the first item (index 0) when its content changes ?
<ComboBox Name="WeeksComboBox" IsEditable="False"
ItemsSource="{Binding Weeks}"
SelectedIndex="{Binding WeekNumber}"
>
Weeks is a Notifying property that is a list of strings. It is changed when i change the Year property. WeekNumber is a notifying property of type integer. Now when it is set to -1, i set the corresponding private member to 0 to avoid wrong value in my model.
I always do that in the code-behind when I change the source
For example,
An alternative is to use the
PropertyChangenotificationOf course, that only works if you actually set
Weeksto a new collection. If you simply clear it and reset it, you’ll have to use theCollectionChangedevent