【问题标题】:Some special characters are not restricted using Regex in KeyDown event in WPF在 WPF 的 KeyDown 事件中使用 Regex 不限制某些特殊字符
【发布时间】:2016-07-12 03:03:06
【问题描述】:

我正在尝试限制除英文字母之外的所有字符,但我仍然可以输入一些不好的顽皮字符!我怎样才能防止这种情况。我的正则表达式没有捕捉到这些顽皮的字符是- _ + = ? < > '

private void AlphaOnlyTextBox_OnKeyDown(object sender, KeyEventArgs e)
{    
    var restrictedChars = new Regex(@"[^a-zA-Z\s]");

    var match = restrictedChars.Match(e.Key.ToString());

    // Check for a naughty character in the KeyDown event.
    if (match.Success)
    {
        // Stop the character from being entered into the control since it is illegal.
        e.Handled = true;
    }
}

<Window x:Class="WpfApplication4.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>

        <TextBox Height="21"
                 Width="77" 
                 MaxLength="2"
                 KeyDown="AlphaOnlyTextBox_OnKeyDown"
                                           >
        </TextBox>
    </Grid>
</Window>

【问题讨论】:

  • 正则表达式似乎抓住了那些(在 regexr.com 上测试过)。你确定问题不在其他地方吗?
  • 是的,问题must be somewhere else
  • @rtmh 您可以在 WPF/C# 中轻松构建问题。由于某些奇怪的原因,它不起作用!
  • @rtmh 一个建议!也许它与按下 Shift 按钮有关!因为我们需要按那个来输入+?
  • 我不会说我们可以轻松构建它。至于那个问题,请查看 KeyEventArgs::Key 函数的细节,它是否返回您期望的结果?

标签: c# regex


【解决方案1】:

试试这个表达式:

var restrictedChars = new Regex(@"[^(\W_0-9)]+");

它将排除除大小字母字符之外的所有字符(不取决于特定语言)。

希望对你有帮助!

【讨论】:

  • 谢谢,但它排除了一切!即使是普通的字母!
  • 确保在表达式中使用大写“W”,因为小写“w”可能会导致您遇到的问题用我的回答中的表达。
  • 感谢意大利,问题似乎出在其他地方,请参阅下面的答案。
【解决方案2】:

在头疼之后,我意识到由于某些我不知道的原因,KeyDown 事件不会捕获某些字符,但 PreviewTextInput 可以!

    private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
    {
        var restrictedChars = new Regex(@"[^a-zA-Z\s]");

        var match = restrictedChars.Match(e.Text);

        // Check for a naughty character in the KeyDown event.
        if (match.Success)
        {
            // Stop the character from being entered into the control since it is illegal.
            e.Handled = true;
        }
    }

    <TextBox Height="21"
             Width="77" 
             MaxLength="2"
             PreviewTextInput="UIElement_OnPreviewTextInput"
                                       >
    </TextBox>

如果您还想禁用空格键:

    <TextBox Height="21"
             Width="77" 
             MaxLength="2"
             PreviewTextInput="UIElement_OnPreviewTextInput"
             PreviewKeyDown="UIElement_OnKeyDown"
                                       >
    </TextBox>

    private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Space)
        {
            e.Handled = true;
        }
    }

【讨论】:

  • 我知道一定有更好的东西,很好的发现。 :)
猜你喜欢
  • 2014-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多