创建一个只接受数字WPF的TextBox [英] Create WPF TextBox that accepts only numbers

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

问题描述

我想创建一个文本框只接受数字值,在一个特定的范围。
什么是实现这些文本框的最佳方式?

I would like to create a TextBox that only accepts numeric values, in a specific range. What is the best way to implement such TextBox?

我想过派生文本框和覆盖TextProperty的验证和胁迫。但是,我不知道如何做到这一点,据我所知,得出WPF控件一般不推荐。



编辑:

我需要的是一个非常基本的文本框,过滤掉所有关键presses哪些不是数字。
实现这一目标最简单的方法是处理文本框previewTextInput事件:

I thought about deriving TextBox and to override the validation and coercion of the TextProperty. However, I am not sure how to do this, and I understand that deriving WPF control is generally not recommended.



What I needed was a very basic textbox that filters out all key presses which are not digits. The easiest way to achieve it is to handle the TextBox.PreviewTextInput event:

private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    int result;
    if (!validateStringAsNumber(e.Text,out result,false))
    {
        e.Handled = true;
    }
}

(validateStringAsNumber是我的函数,它主要使用Int.TryParse)

(validateStringAsNumber is my function that primarily use Int.TryParse)

一些建议的解决方案都可能会更好,但对于简单的功能,我需要这个解决方案是最简单快捷的同时,充分满足我的需求来实现。

Some of the suggested solutions are probably better, but for the simple functionality I needed this solution is the easiest and quickest to implement while sufficient for my needs.

推荐答案

我已经看到,到目前为止,用<一大部分实现href=\"http://msdn.microsoft.com/en-us/library/system.windows.uielement.$p$pviewtextinput.aspx\">$p$pviewTextInput活动实施正确的面具行为。 这一次从文本框和的this~~V 之一使用附加属性。两者都使用NET的<一个href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.maskedtextprovider.aspx\">MaskedTextProvider提供正确的面具行为,但如果你只是想要一个简单的数字只有文本框,你不需要这个类。

Most implementations I have seen so far are using the PreviewTextInput event to implement the correct mask behavior. This one inherits from TextBox and this one uses attached properties. Both use .Net's MaskedTextProvider to provide the correct mask behaviour, but if you just want a simple 'numbers only' textbox you don't need this class.

这篇关于创建一个只接受数字WPF的TextBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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