Is there any decent way to get a WPF control which is bound to a decimal value?
When I just bind the TextBox or DataGridTextColumn to a decimal, data entry sucks big time.
<TextBox Text="{Binding MyDecimal, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
When I try to enter "0,5" in this TextBox I'll get "5" as a result. It is nearly impossible to enter "0,5" at all (Apart from entering 1,5 and replacing the "1" with a "0").
When I use StringFormat data entry still sucks small time:
<TextBox Text="{Binding MyDecimal, StringFormat=F1, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
Now when I try and enter "0,5" I'll end up with "0,5,0", which still is wrong but at least I can remove the trailing ",0" without much Problems.
Still, entering decimals using WPF sucks big time because this entry fields are very prone to data entry errors, which is a real pain especially for values!
So what am I supposed to use for decimal data entry in wpf? Or does Microsoft not support decimal data??
Im new, so I cant comment his answer, but I fixed the negative number issues in blindmeis's code.
Just modify the
section of IsValidInput() to...
I also came across this issue; with
UpdateSourceTrigger=PropertyChanged
it seems that the binding tries to update the text as you are typing it. To fix this issue we changed our input fields so thatUpdateSourceTrigger=LostFocus
, e.g.:You can define your own validation errors by using the
IDataErrorInfo
interface. You just need to add the following to your backing model:I implemented my own TextBox. It updates the source, when there is a number in the text, otherwise not. On lost Focus, I read the source property. All you have to do is replace the TextBox with this class and bind the "Number" Property which is of type double.
This regex works
if you want the textbox to only allow decimal then write previewinputtext event for that textbox. then in that event write this code
The WPF Extended toolkit has a DecimalUpDown control that may suit your needs. It's free to use, and it's better to use this than to try and roll your own.
As for validating the input on it, there are a number of ways of applying validation, here is one detailed in MSDN. I detail another approach for custom bindable validation in two posts on my blog (you would apply the validation to the
Value
property binding on the DecimalUpDown control).