0

如果在 xaml 中有一个文本框。我只想在文本框中写入数值以验证按钮。我该怎么做 ?

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

3 回答 3

4

您可以使用numericUppDown而不是textbox只有数字输入。这就是这样做的方法。

于 2012-11-06T15:03:39.983 回答
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" />
于 2012-11-06T16:17:07.400 回答
0

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

于 2012-11-28T12:01:09.510 回答