Thursday, 6 June 2013

WPF Binding Integer Validation with Null Values

I found a small hole in an application I am developing where a null value in a textbox bound to an integer value wouldn’t get validated.

It was slightly more complicated than that however. The xaml was as follows;

<TextBox Text="{Binding MyTextBoxText, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay}"/>

Where my Validation was set for when the control lost focus.

When I added a new record, the value of the binding was set to null, this enforced by validation correctly. Same when I edited the text and left the control. However, if I edited the control when it had a value, say changing the value from a 2 to nothing, then the validation wouldn’t occur.

This was because the binding didn’t have a value for a null entry. Adding a TargetNullValue parameter to the binding and thus changing the binding to the following fixed the issue nicely;



<TextBox Text="{Binding TaskOrder, UpdateSourceTrigger=LostFocus, ValidatesOnDataErrors=True, NotifyOnValidationError=True, Mode=TwoWay, TargetNullValue=''}"/>

More information on the TargetNullValue Property can be found here;

http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.targetnullvalue.aspx

No comments:

Post a Comment