WPF Text Box Validation on numeric value

久未见 提交于 2019-12-13 04:33:40

问题


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>

回答1:


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" />



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/13251506/wpf-text-box-validation-on-numeric-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!