C#中的数字文本框 - WPF

Kou*_*osh 6 c# wpf textbox numbers

我想在WPF中创建一个只接受数字的文本框...我已经重新申请并且人们说使用按键事件或屏蔽文本框,但它们是在Windows窗体中...

小智 33

对于WPF:

private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (!char.IsDigit(e.Text, e.Text.Length - 1))
        e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

对于Windows窗体:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) )
        e.Handled = true;
}
Run Code Online (Sandbox Code Playgroud)

  • 小心将复制粘贴到您的盒子中,不会被这样的代码控制 (5认同)