WPF StringFormat to allow only positive numbers
I only want to allow positive numbers as user input in my TextBox.
If I input -10
and use
<TextBox Text="{Binding Width, StringFormat={}{0:0.00;0.00}}" />
then it always displays positive numbers, but the Data behind is still negative.
How to do it right?
Solution 1:
There are a number of ways to handle this, such as OmegaMan's. But my solution for this would be to not use a textbox at all. Sadly WPF has never been blessed with a spinbox/updown control out of the box, but the extended WPFToolkit does have one. So why waste your time on parsing and handling all the nasty cases? Let the control do the heavy lifting.
<extToolkit:IntegerUpDown Value="{Binding Width}" Minimum="0"/>
Done
Solution 2:
Since the validation rule enforces the value to be positive, I suggest to also check the value in the VM property to enforce/convert it as well:
private string _width;
public string Width
{
get { return _width; }
set
{
int result;
int.TryParse(value, out result);
_width = (result < 0 ? result *-1 : result).ToString();
PropertyChanged("Width");
}
}