My ComboBox
:
<ComboBox
SourceUpdated="MyComboBox_SourceUpdated"
ItemsSource="{Binding ...}"
SelectedValue="{Binding Path=SelectedValueMember, NotifyOnSourceUpdated=True}"
SelectedValuePath="..."
DisplayMemberPath="..."
/>
And my SourceUpdated
handler:
private void MyComboBox_SourceUpdated(object sender, DataTransferEventArgs args) {
if (/* user answers no to an 'are you sure?' prompt */) {
// TODO: revert ComboBox back to original value
}
}
I'm having difficult reverting the ComboBox back to its original value (in the "TODO" comment of my code above).
The first and most obvious thing I tried was to simply change back the value of the SelectedValueMember of the DataContext, assuming the binding would update the ComboBox:
MyDataContext.SelectedValueMember = original_value;
When I do this, in the debugger I can see that it is indeed updating the SelectedValueMember value, but the ComboBox does not change back - it holds onto the new value.
Any ideas?
AngelWPF's answer below works and is probably the neatest and clearest way.
I did however, find a non-obvious solution:
private void MyComboBox_SourceUpdated(object sender, DataTransferEventArgs args) {
if (/* user answers no to an 'are you sure?' prompt */) {
Dispatcher.BeginInvoke(new Action(() => {
MyDataContext.SelectedValueMember = original_value;
}));
}
}
Just by putting the operation on a second UI thread by means of BeginInvoke
, it works! I could be wrong, but my hunch is that to avoid binding update loops, the actions directly in Source/Target Updated handlers are not reacted to by bindings.