I am using the MVVM pattern to bind a ComboBox SelectedIndex value to an int in the view model:
<ComboBox ItemsSource="{Binding DropdownListChoices}" Margin="5,2,5,1" Width="320" Height="23"
Style="{StaticResource comboBoxWithErrorHandling}" SelectedIndex="{Binding SelectedComboBoxIndex}">
View model:
public class FieldViewModel : ObservableObject, IDataErrorInfo
{
private int _selectedComboBoxIndex;
public int SelectedComboBoxIndex
{
get { return _selectedComboBoxIndex; }
set
{
if (_selectedComboBoxIndex != value)
{
_selectedComboBoxIndex = value;
RaisePropertyChanged("SelectedComboBoxIndex");
}
}
}
// ...
}
In a different part of the code, I populate DropdownListChoices. Let’s say the elements are for instance A, B, C, A, D. Selecting B, C or D correctly causes SelectedComboBoxIndex to get the expected value (1, 2 or 4, respectively). But selecting A will set SelectedComboBoxIndex to 0, regardless of whether the first or the second A was selected. On selecting the second A, I would expect the selected index to be 3.
Why does this happen? Is there a different way of achieving what I’m trying to do, namely to get the absolute list index which was selected?
You should never have duplicate items in selector-controls, it will only confuse them and cause anomalies, if you have primitive values wrap them in a class.