0

xamlにテキストボックスがある場合。ボタンで検証するには、テキストボックスに数値のみを書き込むことができます。どうすればできますか?

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

3 に答える 3

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 に答える
4

numericUppDownの代わりに使用textboxして、数値入力のみを行うことができます。それがその方法です。

于 2012-11-06T15:03:39.983 に答える
0

wpf 動作制御を使用します。例 http://wpfbehaviorlibrary.codeplex.com/

于 2012-11-28T12:01:09.510 に答える