Dutton

OK - Cancel behaviour with data binding in WPF

As much as I am a fan of the Mac OSX and iPhone approach of modifying a setting and having it apply immediately without any further user interaction, my current work involves designing GUIs for Industrial Control and Automation systems where the old <OK> <Cancel> buttons are still required (often by law) which brought up the question of how to do this in WPF with data binding where, depending on the control, updates are triggered either in real-time or on loss of focus.

The answer is in one of the attributes of Binding called "UpdateSourceTrigger" which has the following options:

It is this last setting which allows us to delay updating our bound property until we tell it to.

Let's say we have a UserControl containing a TextBox, 'MyTextBox' which is bound to some Dependency Property and two buttons, 'OK' and 'Cancel'. Depending on how you hook your buttons up (with RoutedCommands or click handlers (eugh!)) the 'OK' button's code looks like this:

BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (be!=null) be.UpdateSource();

The 'Cancel' button's code does the reverse:

BindingExpression be = MyTextBox.GetBindingExpression(TextBox.TextProperty);
if (be!=null) be.UpdateTarget();

Et voila! Your dependency property will now only update when you want it to.


Share this: