xamlにテキストボックスがある場合。ボタンで検証するには、テキストボックスに数値のみを書き込むことができます。どうすればできますか?
<TextBox x:Name="txtLevel" Grid.Column="1" HorizontalAlignment="Stretch"></TextBox>
xamlにテキストボックスがある場合。ボタンで検証するには、テキストボックスに数値のみを書き込むことができます。どうすればできますか?
<TextBox x:Name="txtLevel" Grid.Column="1" HorizontalAlignment="Stretch"></TextBox>
以下のように、テキストボックスへのすべての追加をホストするクラスを作成します。数値の入力を停止するビットは、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" />
numericUppDown
の代わりに使用textbox
して、数値入力のみを行うことができます。それがその方法です。
wpf 動作制御を使用します。例 http://wpfbehaviorlibrary.codeplex.com/