I have a ComboBox's SelectedItem property bound to an object's field. It uses TwoWay binding, which works fine in most cases; when it loads up, the dropdown's selection is set from the field's getter, and manually changing the selection calls the field's setter.
However, sometimes I want to display a confirmation dialog. If the user clicks "No", I want the value to stay the same. Here is my code:
public A Afield
{
get { return _afield; }
set
{
SetA(value);
}
}
public void SetA(LocationConfiguration value, bool prompt = true)
{
if (/*selection would cause irreversible changes*/)
{
if (prompt)
{
MessageBoxResult result = Microsoft.Windows.Controls.MessageBox.Show(
"bla bla bla",
"bla",
MessageBoxButton.YesNo,
MessageBoxImage.Warning);
if (result != MessageBoxResult.Yes)
return;
}
PerformIrreversibleChanges()
}
_afield = value;
NotifyPropertyChanged("Afield");
}
Everything in the codebehind works perfectly. If the user accepts, the changes are made. If the user presses "No", _afield is not modified. Other controls bound to this property show the correct value.
However, the ComboBox display does NOT revert to the value of _afield. It stays as whatever they selected, even if they rejected the change. For some reason it seems like it doesn't set the item of the combobox until after the property is set. At that point it displays what the user selected, not the correct value that persists in the codebehind.