在文本框中限制字符数

6
我正在构建一个C# WinRT应用程序中的表单,并且我想限制其中一个TextBox组件中的字符只能是数字。(这个TextBox将用于用户输入年份。)
我已经搜索了一段时间,但没有找到不设置TextChanged事件监听器并检查每次按键时的text属性就能解决此问题的方法。有没有一种简单的方法可以只允许用户在TextBox中输入特定的字符?
6个回答

8
最简单的方法就是绑定到 OnTextChanged 事件,并根据您的规则修改文本。
    <TextBox x:Name="TheText" TextChanged="OnTextChanged" MaxLength="4"/>

    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        if (TheText.Text.Length == 0) return;

        var text = TheText.Text;

        int result;
        var isValid = int.TryParse(text, out result);
        if (isValid) return;

        TheText.Text = text.Remove(text.Length - 1);
        TheText.SelectionStart = text.Length;
    }

然而,我会避免使用这种方法,因为Metro的口号是“触摸优先UI”,您可以轻松地通过FlipView控件以触摸优先的方式实现。


将其标记为答案,因为它基本上解决了我遇到的问题。这将限制TextBox仅显示数字。但是,我已经重新访问了我的应用程序的这一部分,并用ComboBox替换了年份字段,以完全避开这个问题。(我有一个固定的年份范围,所以我不知道为什么我一开始没有使用ComboBox。) - Josh Buhler

6

这很酷,在WPF中也(有点)存在。以前不知道这个。谢谢! - Avner Shahar-Kashtan
1
这种方式可以使用,但无法完全实现我的目标。看起来InputScope属性更像是向系统提供提示,告诉系统应该显示哪个软键盘,但它不会创建限制输入的掩码TextBox。(终于在MSDN论坛上找到了这个帖子-请参见下面的链接,查看来自2012年3月22日周四下午5:49的Chipalo街帖子)http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/d746d7d7-91c7-4429-8efa-a748b4ce6a03 - Josh Buhler
啊,看来我误解了文档。谢谢你指出来。 - sdb

0

这对我来说似乎有效:

    private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        if ((e.Key < VirtualKey.Number0) || (e.Key > VirtualKey.Number9))
        {
            // If it's not a numeric character, prevent the TextBox from handling the keystroke
            e.Handled = true;
        }
    }

请参阅VirtualKey枚举的文档以获取所有值。

0

有效年份

DateTime newDate;
var validYear = DateTime.TryParseExact("2012", "yyyy", CultureInfo.InvariantCulture, 
DateTimeStyles.None, out newDate); //valid

无效的年份

var validYear = DateTime.TryParseExact("0000", "yyyy", CultureInfo.InvariantCulture, 
DateTimeStyles.None, out newDate); //invalid

0
基于链接的帖子,添加选项卡以实现导航。
private void decimalTextBox_KeyDown(object sender, KeyRoutedEventArgs e)
    {
        bool isGoodData;    // flag to make the flow clearer.
        TextBox theTextBox = (TextBox)sender;  // the sender is a textbox

        if (e.Key>= Windows.System.VirtualKey.Number0 && e.Key <= Windows.System.VirtualKey.Number9)  // allow digits
            isGoodData = true;
        else if (e.Key == Windows.System.VirtualKey.Tab)
            isGoodData = true; 
        else if (e.Key >= Windows.System.VirtualKey.NumberPad0 && e.Key <= Windows.System.VirtualKey.NumberPad9)  // allow digits
            isGoodData = true;
        else if (e.Key == Windows.System.VirtualKey.Decimal || (int)e.Key == 190)   // character is a decimal point, 190 is the keyboard period code
                                                                                    // which is not in the VirtualKey enumeration
        {
            if (theTextBox.Text.Contains("."))   // search for a current point
                isGoodData = false;    // only 1 decimal point allowed
            else
                isGoodData = true;     // this is the only one.
        }
        else if (e.Key == Windows.System.VirtualKey.Back)  // allow backspace
            isGoodData = true;
        else
            isGoodData = false;   // everything else is bad
        if (!isGoodData)          // mark bad data as handled
            e.Handled = true;
    }

1
Shift-4应该是一个美元符号,但这段代码没有过滤掉它。4键被视为数字并被接受。请参考以下问题:https://dev59.com/uWcs5IYBdhLWcg3wRBtQ其中展示了各种检测shift、control等按键的方法。 - David Rector

-2
使用 MaskedTextBox 控件。仅使用 Mask 属性指定字符和长度即可输入数字。例如,如果您只希望输入五个数字,将掩码属性设置为“00000”。就这么简单。Windows 会为您处理限制。

1
WinRT有MaskedTextBox吗? - Ritch Melton
@RitchMelton 我现在不知道。我猜答案应该是肯定的。 - olatunjee
当前文档显示不支持。http://msdn.microsoft.com/zh-cn/library/windows/apps/windows.ui.xaml.controls.aspx - Ritch Melton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接