如何让 TextBox 只接受 WPF 中的数字输入?

2023-11-24

我希望接受数字和小数点,但没有符号。

我查看了使用 Windows 窗体 NumericUpDown 控件的示例,并且Microsoft 的 NumericUpDown 自定义控件示例。但到目前为止,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 event 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();
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何让 TextBox 只接受 WPF 中的数字输入? 的相关文章

随机推荐