I want to implement decimal number validation on WPF TextBoxes.
I found an answer for WPF TextBox validation on numeric values, but I want a TextBox that allows decimal values (float/double) as well.
How can I do this?
public static bool GetIsDecimal(DependencyObject obj)
{
return (bool)obj.GetValue(IsDecimalProperty);
}
public static void SetIsDecimal(DependencyObject obj, bool value)
{
obj.SetValue(IsDecimalProperty, value);
}
public static readonly DependencyProperty IsDecimalProperty =
DependencyProperty.RegisterAttached("IsDecimal", typeof(bool), typeof(TextBoxHelpers), new PropertyMetadata(false, new PropertyChangedCallback((s, e) =>
{
TextBox targetTextbox = s as TextBox;
if (targetTextbox != null)
{
if ((bool)e.OldValue && !((bool)e.NewValue))
{
targetTextbox.PreviewTextInput -= targetTextbox_PreviewTextInput;
}
if ((bool)e.NewValue)
{
targetTextbox.PreviewTextInput += targetTextbox_PreviewTextInput;
targetTextbox.PreviewKeyDown += targetTextbox_PreviewKeyDown;
}
}
})));
static void targetTextbox_PreviewKeyDown(object sender, KeyEventArgs e)
{
e.Handled = (e.Key == Key.Space);
}
static void targetTextbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Char newChar = e.Text.ToString()[0];
e.Handled = !(Char.IsNumber(newChar) || (newChar == '.'));
}
}
I am using the above code. The code (Char.IsNumber(newChar) || (newChar == '.'))
will check for numbers and decimals. So now the TextBox allows only numbers and decimal(.). But the problem is that, I can enter multiple decimal points (For example, 1.01.22.011). So I want to restrict entering multiple decimal points.
you can use a behavior
behavior.cs:
C# Code :