6

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

4

1 回答 1

33

对于 WPF:

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

对于 Windows 窗体:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) )
        e.Handled = true;
}
于 2013-07-06T17:46:59.420 回答