How do I cancel a databinding property set in WPF?

I have a combobox in WPF that I am using the SelectedItem property with a DataBinding and sometimes certain items shouldn’t be selected based on certain criteria. Mine was that two comboboxes couldn’t have the same value.

Yes, there are other ways, such as removing invalid values from other boxes, but here was my solution for preventing the invalid property set by cancelling the selection/property set.

WPF sucks in this manner as there isn’t an easy way to update it. You can’t raise the property updated event since the binding ignores those when setting, to avoid recursion issue I suppose. (Yes, developers could defend by not raising the events if the property doesn’t change)

Anyway, the solution is simply to raise the property changed after the operation, by simply posting it to the work queue on the UI thread right afterward.


Code: in C#

public MyHeaderType SelectedHeader
          get { return this.selectedHeader; }
              bool resetMe= validateValue(value);
              var origVal = selectedHeader;//store for reset

              selectedHeader = value;
              RaisePropertyChanged(() => SelectedHeader);

              if (resetMe)//Why do I need to set the value above? No idea. Doesn’t work unless I do it that way. Yes. I tried.
                  Application.Current.Dispatcher.BeginInvoke( //force a reenter to put it back……
                                new Action(() =>
                                    SelectedHeader = origVal;//put me back to the correct value.




Happy Coding!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.