WPF文本框验证数值

时间:2012-11-06 12:54:01

标签: wpf wpf-controls

如果在xaml中有一个文本框。我想只需要在文本框中写入数值即可在按钮上进行验证。我该怎么做 ?

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

3 个答案:

答案 0 :(得分:4)

您可以使用numericUppDown代替textbox,以便只使用数字输入。这是做到这一点的方法。

答案 1 :(得分:4)

我会创建一个类来托管你想要制作的文本框的所有新增内容,阻止你输入数字的位在PreviewTextInput的事件处理程序中,如果它不是数字我只是说事件被处理并且文本框永远不会得到值。

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);
    }
}

要在XAML中使用带附加属性的辅助类,您需要为其指定一个名称空间,然后像这样使用它。

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

答案 2 :(得分:0)

使用wpf行为控制。例 http://wpfbehaviorlibrary.codeplex.com/