我有一个数据绑定的 WPF 文本框。我需要限制文本框上的用户输入,以便它只接受数字和一个句点(用于显示小数)。
我知道我可以以“Winforms”的方式处理这个问题并验证 KeyPress 事件上的每个输入,但我想知道在 WPF 中是否有更清洁甚至是正确的方法来执行此操作(特别是因为我正在对文本框进行数据绑定)。
使用 WPF 提供的 ValidationRules。
xaml 将是:
<TextBox>
<TextBox.Text>
<Binding Path="Name">
<Binding.ValidationRules>
<ExceptionValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
文本框属性的代码将是(使用正则表达式进行验证):
public string Name
{
get { return _name; }
set
{
_name = value;
if (!Regex.IsMatch(value, @"^((?:[1-9]\d*)|(?:(?=[\d.]+)(?:[1-9]\d*|0)\.\d+))$"))
{
throw new ApplicationException("Please enter only numbers/decimals.");
}
}
}
来源:WPF 中的验证
上面给出的正则表达式:^((?:[1-9]\d*)|(?:(?=[\d.]+)(?:[1-9]\d*|0)\.\d+))$
可以在这个Rubular 链接上进行测试
正则表达式将匹配这些:
1.2
22522
0.33
3.90000
但不是这些:(您可以调整正则表达式以允许其中一些)
.999
23.35.1343
03423.23423
数据绑定将影响传递给/从您数据绑定到的对象的值。要阻止用户按键,您要么需要使用屏蔽文本框(在 winforms 中,不确定 WPF),要么您需要处理文本框中的 KeyPressedEvent 并停止您不想按下的键。
我使用下面的代码只允许数字和一位小数
private void textBoxPrice_KeyPress( object sender, KeyPressEventArgs e )
{
if( !char.IsControl( e.KeyChar )
&& !char.IsDigit( e.KeyChar )
&& e.KeyChar != '.' )
{
e.Handled = true;
}
// only allow one decimal point
if( e.KeyChar == '.'
&& ( sender as TextBox ).Text.IndexOf( '.' ) > -1 )
{
e.Handled = true;
}
}
只需使用按键事件,并使用 ascii 字符验证按键事件。
e.KeyCode >47 && e.KeyCode <58 将限制用户不要按数字以外的任何字母。
如果您需要确切的代码示例,请稍等 :)