【问题标题】:How to create a textbox that only accepts numbers and one that only accepts letters in WPF?如何在 WPF 中创建一个只接受数字和一个只接受字母的文本框?
【发布时间】:2013-04-24 22:36:08
【问题描述】:

我只想知道如何创建一个只允许用户输入数字的文本框,一个允许数字和句号的文本框,以及一个只允许用户输入字母的文本框?

我将此代码用于 Windows 窗体:

private void YearText_KeyPress(object sender, KeyPressEventArgs e) //Textbox only accepts numbers
{
    char ch = e.KeyChar;
    if (!Char.IsDigit(ch) && ch != 8 && ch != 13)
    {
        e.Handled = true;
    }
}

private void NameText_KeyPress(object sender, KeyPressEventArgs e) //Textbox only accepts letters
{
    if (!char.IsLetter(e.KeyChar) && !char.IsControl(e.KeyChar) && !char.IsWhiteSpace(e.KeyChar))
        e.Handled = true;
}

private void ResellPriceText_KeyPress(object sender, KeyPressEventArgs e) //Textbox that allows only numbers and fullstops
{
    if (!char.IsControl(e.KeyChar)
        && !char.IsDigit(e.KeyChar)
        && e.KeyChar != '.')
    {
        e.Handled = true;
    }

    // only allow one decimal point
    if (e.KeyChar == '.'
        && (sender as TextBox).Text.IndexOf('.') > -1)
    {
        e.Handled = true;
    }
}

但我很快发现 WPF 无法做到这一点。我不关心诸如粘贴字母/数字之类的事情。

【问题讨论】:

    标签: c# wpf winforms xaml textbox


    【解决方案1】:

    这可以在 WPF 中完成,实际上您甚至可以使用非常相似的基于事件处理程序的代码来完成,但是,不要这样 - 这是一种糟糕的用户体验。这将防止用户在意外包含周围空间时复制和粘贴,并防止输入科学数字,例如100e3.

    改为使用验证(在修剪后的输入上)并在验证失败时阻止用户继续。

    【讨论】:

    • 我支持事后验证的想法。我从来没有发现有必要限制可以输入的内容,只限制可以提交的内容。
    • 输入一个只有 a-f 和 0-9 的 MAC 地址很有用。允许使用超出范围的字符输入 MAC 地址,并使输入无效对我来说似乎很麻烦。所以我想这取决于用例。
    猜你喜欢
    • 2010-10-02
    • 1970-01-01
    • 2010-10-21
    • 2011-04-17
    • 1970-01-01
    • 2022-06-28
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    相关资源
    最近更新 更多