I have an application that has a combobox bound to a viewmodel. I would like to perform validation on the selection, and if the user selects a choice that I don't want them to, I would like to provide feedback that the selection is invalid, and return the SelectedItem to a default value.
I am using IPropertyChanged, the combobox gets its items and selection from a ComboItem class via ObservableCollection, and the binding is working as expected.
The combobox has three items, each with an item number 0-2, and a description.
ComboBox Form Image:
The button on my WPF Test Form returns the value of the SelectedComboItem stored in the view model.
When an item is selected, validation is performed, and if the selected item number is 2 (Description Invalid), then an error window is displayed, and the SelectedComboItem is set back to its default value (hard coded as ComboItems[0] for simplicity).
public ObservableCollection<ComboItem> ComboItems
{
get { return _comboItems; }
set { _comboItems = value; OnPropertyChanged("ComboItems"); }
}
public ComboItem SelectedComboItem
{
get { return _selectedComboItem; }
set { _selectedComboItem = ComboValidation(value); OnPropertyChanged("SelectedComboItem"); }
}
//************************
private ComboItem ComboValidation(ComboItem item)
{
if(item.Item == 2)
{
MessageBox.Show("This is an invalid selection", "ComboTest");
return ComboItems[0];
}
return item;
When I select the valid items (Item 1, Item 2), the combobox reacts and the viewmodel data is as expected.
Item 2 Combo = ViewModel Selection:
However, when I select the invalid item (Item 3), the viewmodel SelectedComboItem property changes as expected, but the WPF combobox that it is bound to retains the invalid item.
WPF Combobox Shows Invalid, ViewModel Shows Default Value:
I assume what is happening is that the initial value is being stored for use by the form refresh, even though it happens after the validation and value change. How can I refresh the form to ensure that it refreshes to the validated data?
Test Application Here: https://github.com/jtprichard/WPFComboTest