簡體   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