创建只接受数字的 WPF 文本框 [英] Create WPF TextBox that accepts only numbers

查看:19
本文介绍了创建只接受数字的 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?

我想过派生 TextBox 并覆盖 TextProperty 的验证和强制.但是,我不确定如何执行此操作,并且我知道通常不建议派生 WPF 控件.<小时>
我需要的是一个非常基本的文本框,它可以过滤掉所有不是数字的按键.实现它的最简单方法是处理 TextBox.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.

推荐答案

到目前为止,我看到的大多数实现都是使用 PreviewTextInput 事件来实现正确的掩码行为.这个继承自TextBox和这个使用附加属性.两者都使用 .Net 的 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 文本框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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