如何让 TextBox 只接受 WPF 中的数字输入? [英] How do I get a TextBox to only accept numeric input in WPF?

查看:27
本文介绍了如何让 TextBox 只接受 WPF 中的数字输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking to accept digits and the decimal point, but no sign.

我查看了使用 Windows 窗体的 NumericUpDown 控件的示例,以及 thisMicrosoft 的 NumericUpDown 自定义控件示例.但到目前为止,似乎 NumericUpDown(是否受 WPF 支持)不会提供我想要的功能.我的应用程序的设计方式,没有人会想弄乱箭头.在我的应用程序上下文中,它们没有任何实际意义.

I've looked at samples using the NumericUpDown control for Windows Forms, and this sample of a NumericUpDown custom control from Microsoft. But so far it seems like NumericUpDown (supported by WPF or not) is not going to provide the functionality that I want. The way my application is designed, nobody in their right mind is going to want to mess with the arrows. They don't make any practical sense, in the context of my application.

所以我正在寻找一种简单的方法来使标准 WPF 文本框只接受我想要的字符.这可能吗?实用吗?

So I'm looking for a simple way to make a standard WPF TextBox accept only the characters that I want. Is this possible? Is it practical?

推荐答案

添加预览文本输入事件.像这样:<TextBox PreviewTextInput="PreviewTextInput"/>.

Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.

然后在里面设置 e.Handled 如果文本不被允许.e.Handled = !IsTextAllowed(e.Text);

Then inside that set the e.Handled if the text isn't allowed. e.Handled = !IsTextAllowed(e.Text);

我在 IsTextAllowed 方法中使用了一个简单的正则表达式来查看我是否应该允许他们输入的内容.就我而言,我只想允许数字、点和破折号.

I use a simple regex in IsTextAllowed method to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.

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" 如图所示这里(代码摘录):

If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting" as shown here (code excerpted):

// 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();
    }
}

这篇关于如何让 TextBox 只接受 WPF 中的数字输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆