備忘録

備忘録

C# WPF 数値のみ入力できるTextBoxを作る

Ⅰ. はじめに

半角数値0~9のみを許可するTextBoxの作り方です。
数値のみ入力可能なTextBoxは標準機能として用意されていません。(2017/02/20時点)
入力値が数値かどうかを判定するコードを書く必要があります。

Ⅱ. 作り方

1. MainWindow.xaml

<TextBox
  x:Name="textBoxPrice"
  InputMethod.IsInputMethodEnabled="False"
  PreviewTextInput="textBoxPrice_PreviewTextInput"
  CommandManager.PreviewExecuted="textBoxPrice_PreviewExecuted"/>

2. MainWindow.xaml.cs

private void textBoxPrice_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // 0-9のみ
  e.Handled = !new Regex("[0-9]").IsMatch(e.Text);
}
private void textBoxPrice_PreviewExecuted(object sender, ExecutedRoutedEventArgs e)
{
  // 貼り付けを許可しない
  if (e.Command == ApplicationCommands.Paste)
  {
    e.Handled = true;
  }
}