如何制作只允许整数值的文本框?

3 c# wpf

我想在我的wpf应用程序中创建一个只接受整数值的文本框.如果有人在[az]之间键入字符,文本框将拒绝它.因此它不会显示在文本框中

小智 7

您可以处理PreviewTextInput事件:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // Filter out non-digit text input
  foreach (char c in e.Text) 
    if (!Char.IsDigit(c)) 
    {
      e.Handled = true;
      break;
    }
}
Run Code Online (Sandbox Code Playgroud)