Rajeev Kumar
Rajeev Kumar

Reputation: 4963

WPF Text Box Validation on numeric value

if have a text box in xaml. i want only numeric values can be write in textbox to validate on button. how can i do it ?

<TextBox x:Name="txtLevel" Grid.Column="1" HorizontalAlignment="Stretch"></TextBox>

Upvotes: 0

Views: 7091

Answers (3)

sergeyxzc
sergeyxzc

Reputation: 615

Use wpf behavior control. Example http://wpfbehaviorlibrary.codeplex.com/

Upvotes: 0

Andy
Andy

Reputation: 6466

I would create a class to host all of the additions to textbox that you want to make like below, the bit that stops you putting numbers is in the event handler for PreviewTextInput, if it's not numeric I just say the event is handled and the textbox never gets the value.

public class TextBoxHelpers : DependencyObject
{

    public static bool GetIsNumeric(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsNumericProperty);
    }

    public static void SetIsNumeric(DependencyObject obj, bool value)
    {
        obj.SetValue(IsNumericProperty, value);
    }

    // Using a DependencyProperty as the backing store for IsNumeric.  This enables animation, styling, binding, etc...
           public static readonly DependencyProperty IsNumericProperty =
        DependencyProperty.RegisterAttached("IsNumeric", 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);
    }
}

To use the helper class with attached property in XAML you need to point a namespace to it then use it like this.

<TextBox local:TextBoxHelpers.IsNumeric="True" />

Upvotes: 4

Vida Fs
Vida Fs

Reputation: 41

You can use numericUppDown instead of textbox so as to have only numeric input. That is the way to do it.

Upvotes: 4

Related Questions