Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databound nullable values not updated in Silverlight XAML

In my MVVM project I have two textboxes one of which is bound to a nullable integer field of my object and the other to a string field. When the view loads if I enter any value to the textbox bound to the string property I can see that its value gets updated to the object's string property.

However the problem arises when I have entered a value to the textbox that is bound to the nullable integer field of my object. If it is a proper integer value then the value gets updated. If I put an alphanumeric string in the textbox bound to the nullable integer field of my object or if I just leave it blank then the nullable integer field of my object doesnt get updated. It still retains whatever was set earlier.

For eg. if I entered a number '7' to the numeric textbox it will get updated to 7. Now if I change it from '7' to say '7a' or 'a7' or 'asd' or leave it blank. The value still stays as 7 which was the earlier value.

Any work arounds to this problem other than changing the nullable type?

Thanks for your time...

like image 926
user20358 Avatar asked Jan 05 '11 13:01

user20358


2 Answers

If you had your textbox masked to only accept numeric values you can also use:

Text={Binding PropertyName, Mode=TwoWay, TargetNullValue=''}

This will correctly set the bound int? property to null when an empty string is detected.

like image 191
anon Avatar answered Nov 15 '22 06:11

anon


Problem here is whenever you enter empty string or alphabet values in your TextBox that is bound to Nullable<Int32>, value of nullable int is not set.

In this case, binding fails while converting a string value to an integer value. And after failing it doesn't set value to null, but just leaves the old value as it is. You can make sure this is happening by debugging.

What you can do to solve this is create a converter. This converter tries to convert a string value to int and when fails to do so, returns null which will be set to nullable int's value.

like image 41
decyclone Avatar answered Nov 15 '22 06:11

decyclone