温馨提示×

WPF设置文本框只能输入数字

wpf
小亿
225
2023-12-19 07:37:49
栏目: 编程语言

要设置WPF中的文本框只能输入数字,可以使用以下几种方法:

  1. 使用正则表达式进行验证:在文本框的TextChanged事件中,使用正则表达式验证输入的内容是否为数字,如果不是则清空文本框内容。
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    string input = textBox.Text;
    if (!Regex.IsMatch(input, "^[0-9]*$"))
    {
        textBox.Text = string.Empty;
    }
}
  1. 使用键盘输入事件进行验证:在文本框的PreviewTextInput事件中,判断输入的字符是否为数字,如果不是则取消输入。
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    TextBox textBox = (TextBox)sender;
    if (!char.IsDigit(e.Text, e.Text.Length - 1))
    {
        e.Handled = true; // 取消输入
    }
}
  1. 使用InputScope属性限制输入类型:将文本框的InputScope属性设置为Number,这样系统会自动显示数字键盘,并限制只能输入数字。
<TextBox InputScope="Number" />

以上是三种常用的方法,你可以根据需求选择适合的方式来实现。

0