'How can I make a WPF TextBox care about a decimal point?
So I have a TextBox that only allows numbers and decimal points. I want the user to only be allowed to enter 1 decimal point.
Here is the code that is triggered on the PreviewTextInput event: (Some of the code is a little redundant, but it does the job)
private void PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox textBox = (TextBox)sender;
if (e.Text == ".")
{
if (textBox.Text.Contains("."))
{
e.Handled = true;
return;
}
else
{
//Here I am attempting to add the decimal point myself
textBox.Text = (textBox.Text + ".");
e.handled = true;
return;
}
}
else
{
e.Handled = !IsTextAllowed(e.Text);
return;
}
}
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
return !regex.IsMatch(text);
}
The problem is that the first decimal point that is entered is not "significant" until it is followed by a number. So, if the user enters 123. and you were to set a breakpoint and check the value of textBox.text it would be 123. I know this is happening because the textBox is bound to a Double so it is trying to be "smart" and forget about those currently "insignificant" values (The ".").
There shouldn't be anything wrong with my code, I was just hoping to force the textBox to hopefully skip over some unnecessary(?) auto-formatting.
Is there a way to make the textBox "care" about that first decimal point?
Possible Duplicate that was never answered.
or
*Is there a different approach to limiting the number of decimals?" (I have done a lot of research in this area, and I don't think there are any other options.)
Solution 1:[1]
if just limiting the charcters you want maybe something like binding with the string format would meet your needs
here is a good example of the format for double
And this would be an example of doing the binding in code to your ViewModel
<TextBox Text="{Binding LimitedDouble,StringFormat={}{0:00.00}}"></TextBox>
Solution 2:[2]
private void txtDecimal_KeyPress(object sender, KeyPressEventArgs e)
{
if (!Char.IsDigit(e.KeyChar) && e.KeyChar != '\b' && e.KeyChar!='.')
{
e.Handled = true;
}
if (e.KeyChar == '.' && txtDecimal.Text.Contains("."))
{
e.Handled = true;
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | tam |
| Solution 2 | Sandeep.R.Nair |
