Binding double to Textbox with validation in windows store apps - c#

I am using prism for windows 8 the BindableBase class to validate the properties, till now I can bind the string properties and validate them with custom validator.
Now I want to bind the double value directly to the view with two way binding.the problem is when user enters any alphabetical character then the setter of that double property doesn't gets fire cause its not a double value and might fires a conversion exception but because of that I cant validate my property.
may I go for the converter ?, but how can I raise validation exception and make the property invalid in converter
Does anyone know how to do this?

Two way binding a double does indeed give some issues in Windows Store apps (input validation, localization, ...). What I usually do is have another property that represents this double as a string and bind the string value. You can also add validation on this string property and check if it does parse to a double with double.TryParse().
Hopefully a better solution for Windoew 10 UWP will be announced in the near future to prevent the need for this hack.

Related

Cursor misbehaving in UWP TextBox

Let's say I have a ViewModel with a data type of float and implements INotifyPropertyChanged interface.
private float Amount;
And then in my UI:
<TextBox Text="{x:Bind Amount, Mode=TwoWay}" />
What happens is that when I'm trying to type the character . (period), the text cursor goes back to the start and just appears right after two presses of period. What could be causing this behavior?
I have tested the code when UpdateSourceTrigger=PropertyChanged as mentioned in the comments. The problem is that PropertyChanged causes the binding to update immediately after each keystroke. Because of this the behavior is quite upredicatable when the input does not contain a valid float. I have seen three different behaviors so far. Once only one digit is entered and period right after that, the binding sometimes converts it to a decimal:
But sometimes this did not happen and the control just let me enter 3. without any change. The behavior is seems really random. The key is that the value that is set to the backing property is then reflected in the UI by virtue of PropertyChanged event and data binding, which causes the text to change and cursor to jump.
Simply said, the problem here is the fact that the property is a float while the input accepts any string. The solution to your problem could be to use a string property for the binding, like AmountText and then in the setter verify that the text is actually a valid float, parse it and manually set the Amount property. This way you would preserve the "immediate" updating of the value as soon as a valid input is entered while you would also avoid the weird behavior you are seeing.
Also check out the WinRTXamlToolkit and its NumericUpDown control, which might be a better solution for your goal as it provides a natural way for the user to enter numeric values.

PoCo validation on Textbox for Integer DataType

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.
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.
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.
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.
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.

WPF: How to show error message in UI thrown from IValueConverter?

I implemented type CustomDoubleConverter which implements IValueConverter.
I included it Converter={StaticResource customDoubleConverter} and corresponding resource in xaml-file.
It works fine.
The question is about error handling.
I would like to check if UI string represents correct double. if no then show one of two messages on label depending on invalid input: empty string or other non-double string.
Which approach should be used to show custom error messages on UI form when error happens during type converting from string?
I tried to do via exceptions, but received unhandled exception. Tip: Do not
throw an exception in a IValueConverter convinced me not to try exceptions any more.
I was able to check double after converting with correct handling of IDataErrorInfo interface in view model of MVVM. But it could be done after successful string to double conversion, which is not the case described above.
I have also ValidatesOnDataErrors="True" and ValidatesOnExceptions="True" for my text box.
I use MVVM approach for design if it is helpful (similar to the one described in WPF Apps With The Model-View-ViewModel Design Pattern).
In short:
I want to parse double from TextBox and show one of three error messages if any on UI label:
empty string (mentioned above),
invalid double string (mentioned above), and
negative number (does not mentioned above, but I handled it via IDataErrorInfo - it is not an issue).
It strictly depends on your UI design, or in other words, how you gonna notify about a problem to user.
I would say use of Dependency Properties. For example.
Let's say user inserts a value in TextBox. The TextBox has a DataError dependency string property. Converter in case of fail, simply sets that property to appropriate user string (can be recovered form localized resource). One time property setuppped, TextBox becomes red, clears content and prints out the error text generated by converter.
I mean the idea is use Dependency Properties, how it will end up in final UI depends on your app design and your choices.
There is also another related SO link :
How to handle exception in Value converter so that custom error message can be displayed
Hope this helps.

WPF How to access the ValidationResult object in the relevant control?

I want to use the ValidationResult object to send information back to the validated field on my form to reformat the data as necessary, for example:
User enters (123)-456-7890 for the phone number, but in our database all phone numbers are of the format 123.456.7890. The ValidationResult object is created with the args (True, "Reformat") and then the logic of the textbox reformats the String into the proper format. Alternatively, I would be okay accessing the validated field's DP's from within the ValidationRule in order to accomplish the same sort of thing.
How could I do this?
This does not sound like a very good idea to me, since you have a binding to a property anyway i would suggest that reformatting logic is applied in the setter of said property. (The binding engine should get the value afterwards in .NET 4 so this fromatting should even be reflected in the control as well)
Alternatively you can use the Converter layer to accomplish the formatting.

Caliburn Micro: Disable button on form validation error

I have a form with a textbox bound to an integer, and a button. Now, when the value of the textbox is invalid, I want to immediately disable the button.
Normally, one would put a Can() method in the VM, and trigger a NotifyOfPropertyChange in the property's setter. However, if the user inputs a non numeric value for example, the textbox is invalid, but the property setter is never called, so I can't notify/disable the button.
So, how do I disable the button, when the user inputs an invalid value that doesn't cause the property setter to get called? My knowledge of CM is limited as I've just started out.
I've found the best approach to this problem is to make the property a string instead and do the necessary string to integer conversion in your property setter. If the conversion is invalid, then you could reset the TextBox value to a default value. This way your property setter will always get fired.
If your model has an integer property, then it makes sense to place the string version on the view model, as this is only really related to the UI, rather than business logic.
If you don't wish the user to be able to input non digit characters, then you can use a masked text box, such as the one included in the Extended WPF Toolkit, or in a third party control suite such as those offered by Telerik or Infragistics.
I'd use a MaskedTextBox instead and set the mask to integer only.

Categories