我希望接受数字和小数点,但没有符号。
我查看了使用 Windows 窗体的 NumericUpDown 控件的示例,以及 this sample of a NumericUpDown custom control from Microsoft .但到目前为止,NumericUpDown(是否受 WPF 支持)似乎不会提供我想要的功能。按照我的应用程序的设计方式,任何头脑正常的人都不会想要弄乱箭头。在我的应用程序上下文中,它们没有任何实际意义。
所以我正在寻找一种简单的方法来使标准 WPF TextBox 只接受我想要的字符。这可能吗?实用吗?
最佳答案
添加预览文本输入事件。像这样:<TextBox PreviewTextInput="PreviewTextInput" />
.
然后在里面设置e.Handled
如果不允许使用文本。 e.Handled = !IsTextAllowed(e.Text);
我在 IsTextAllowed
中使用了一个简单的正则表达式方法来查看我是否应该允许他们输入的内容。在我的例子中,我只想允许数字、点和破折号。
private static readonly Regex _regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
private static bool IsTextAllowed(string text)
{
return !_regex.IsMatch(text);
}
如果您想防止粘贴不正确的数据,请连接 DataObject.Pasting
事件 DataObject.Pasting="TextBoxPasting"
如图here (代码摘录):
// Use the DataObject.Pasting Handler
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
关于c# - 如何让 TextBox 仅接受 WPF 中的数字输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1268552/