PoCo validation on Textbox for Integer DataType

2019-09-02 20:57发布

问题:

I am developing a WPF application in which i am using a textbox that is bind to an int field of my POCO entity, when i clear the textbox i want my currentobject to be invalid as this is a non nullable field.

But the thing is when i clear my textbox, it convert to string.empty that can ot be set to an int value, so my int field never gets updated and my object remains Valid.

Kindly suggest some logical solution to this.

回答1:

One approach is to bind to a string value instead (probably added to a view model if you don't want to pollute your model), and then in the setter for the string property, convert the string to an integer to store on your int property.



回答2:

As i see it, you should not be able to set an 'empty' value to an int control. Maybe you could use the IntegerUpDown control in the Extended WPF Toolkit which allows you to provide a watermark to show text in place of a NULL Value or set a default value, which could be 0.

It also has button spinners, which can be hidden if needed.



回答3:

i copied my answer from here. i hope it helps you too.

if your viewmodel has an Property of type int, then your binding just works if your view got input which is convertable to int. otherwise your viewmodel will never be informed. there are 2 ways now:

first: you make sure that your view just can take numeric input (with your numeric textbox) and the viewmodel property can be int.

or second: your viewmodel property type is typeof string and you use IDataErrorInfo to let the view know when the input is not numeric.



回答4:

By default WPF should display the ErrorTemplate when a validation error occurs, and this includes validation errors caused by invalid casts, such as trying to store a string field in an int. The default ErrorTemplate for a TextBox is a red border, and for most users this is an indication that something is incorrect and the changes will not get saved.

If you want something more than that, you could try using an IValueConverter in your binding which attempts to cast the value into a int, and will return 0 (or some invalid value) if it fails so your object will get updated with something no matter what the user enters.



标签: c# wpf mvvm poco