WPF Binding is extremely powerful and useful - but it does have a few traps for the unwary. Propagation lag is one of them.

While most WPF controls default their bindings with UpdateSourceTrigger set to PropertyChanged, updating the bound property every time the control is changed, TextControl defaults to LostFocus. Updates to the bound property are therefore performed only when the control loses focus.

Couple this with the behaviour of a default button, which triggers when the user presses Return, and code in your model can be executing before any focus change occurs. You end up with the users latest input seemingly ignored. See the demonstration project (attached) to see this in action.

Windows Forms suffered from a very similar DataBinding lag problem, though in that case the bindings triggered when the control was validated, and there was a simple (though not well known) solution: Force the form to validate, and all the bindings will be updated.

An equivalent to the Windows Forms solution doesn’t seem to be built into WPF, leaving us with a couple of possible approaches.

The simplest approach is to change the DataBinding configuration of each TextControl to PropertyChanged so that it updates with every keypress. In most cases, this will work just fine - the exceptions are those cases where you want to do some kind of processing (perhaps formatting) when the value is set.

The alternative approach is to leave the TextControls to work in their default fashion, and to force the binding to update manually when necessary, as described in this StackOverflow answer.

Comments

blog comments powered by Disqus