繁体   English   中英

在WPF的KeyDown事件中使用正则表达式不限制某些特殊字符

[英]Some special characters are not restricted using Regex in KeyDown event in WPF

我正在尝试限制除英语字母之外的所有其他字符,但是我仍然能够输入一些顽皮的字符,这不好! 我该如何预防。 这些不被我的正则表达式捕获的顽皮字符是- _ + = ? < > ' - _ + = ? < > '

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>

试试这个表达式:

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

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

希望能帮助到你!

经过这么多的努力后,我意识到由于某些我不知道的原因, 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;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM