【问题标题】:Only alphabetical chars in WPF text boxWPF 文本框中只有字母字符
【发布时间】:2020-03-18 13:14:37
【问题描述】:

您好,我在使用这些代码时遇到问题:

private void OnlyText(object sender , TextCompositionEventArgs e)
{
  Regex regex = new Regex("^[a-zA-Z]+$");
  e.Handled = regex.IsMatch(e.Text);
}

XAML

<TextBox PreviewTextInput="OnlyText" x:Name="tbSurrname" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="Nazwisko" VerticalAlignment="Top" Width="120" Margin="81,137,0,0"/>

只允许 wpf 文本框使用字母字符,但它没有任何解决方案?

【问题讨论】:

  • 所以您不能在框中输入自己的姓氏?世界不会只说 a-z。

标签: c# regex wpf


【解决方案1】:

欢迎来到 SO!

简单的修复,改变这个:

e.Handled = regex.IsMatch(e.Text);

...到这个:

e.Handled = !regex.IsMatch(e.Text);

【讨论】:

    【解决方案2】:

    虽然我没有看到您的正则表达式有任何问题,但我建议使用

    e.Handled = e.Text.All(ch => char.IsLetter(ch) && ch < 128);
    

    ch &lt; 128 是为了确保我们只有 ASCII 字符。

    正则表达式对于这样简单的任务来说“太重了”。

    我也建议你设置断点,看看e.Text的实际值是多少。

    【讨论】:

    • 请注意,您提出了不同的建议:在您的代码中,ch 可以是任何 Unicode 字母,而 OP 只允许 ASCII 字母。
    • @MichałTurczyn 我在文本框中发现了新问题,我只能写数字字符,不能写字母
    • 那是因为问题与您发布的代码无关。
    • @TomaszCieśliński 然后改用char.IsDigit方法,你可以省略ch &lt; 128条件。
    【解决方案3】:

    解决方案

    private void OnlyAlphabetical(object sender, KeyEventArgs e)
            {
                if ((e.Key < Key.A) || (e.Key > Key.Z))
                {
                    e.Handled = true;
                }
    
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-21
      • 1970-01-01
      • 2022-09-27
      • 2010-10-24
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      相关资源
      最近更新 更多