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

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

问题描述

我希望接受数字和小数点,但不能带符号.

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

我已经使用适用于Windows窗体的NumericUpDown控件查看了示例,并且此Microsoft的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天全站免登陆