WPF Text Box Validation on numeric value

2019-08-28 01:19发布

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>

3条回答
地球回转人心会变
2楼-- · 2019-08-28 02:04

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" />
查看更多
男人必须洒脱
3楼-- · 2019-08-28 02:11

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

查看更多
三岁会撩人
4楼-- · 2019-08-28 02:19

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

查看更多
登录 后发表回答