关于c#:在WPF中的KeyDown事件中使用Regex不限制某些特殊字符

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

我试图限制除英文字母之外的所有字符,但我仍然可以输入一些不好的淘气字符!我怎么能阻止呢?我的正则表达式没有捕捉到这些淘气的字符是- _ + = ? < > '

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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>


非常后我意识到这头挠我的一些未知的原因,KeyDown捕获的事件是不是一定的特点,但不PreviewTextInput

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
    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>

如果你还想空间:禁用按钮

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    <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;
        }
    }


试试这个表达:

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

这将排除所有,但大和小字母字符(不取决于在具体的语言)。

希望它帮助!