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.
For explicit conditional update of a source in a binding, use the updatesource trigger as Explicit and handle the selection changed event of combobox to perform the sync with the source based on the message box result.
So the
ComboBoxis bound to a collection of items (calledMyData) havingNameandIDas properties. The selected value of theComboBoxis bound to another property calledMyID. Now notcie thatUpdateSourceTrigger=Explicitin theSelectedValuebinding.The way I sync the
MyIDwhen the selection changes, with the selected value of the combobox ONLY if user selectsYeson a message box as below…Thsi way there is no need to revert. The source updates explicitly and you have all the control over it.