为什么指定最大长度的正则表达式在 C# wpf 中不起作用

Why the regex that specifies a max length does not work in C# wpf

我试过这个正则表达式,但它不起作用。我可以写任意多的字符,而无需验证停止我的条目。我想知道为什么。特别是,如果我删除处理长度的部分,它工作正常,但我需要在我的项目中处理长度。所以我想知道如何处理 c# regex

中的最大长度
private void AlphaValidationTextBox(object sender, TextCompositionEventArgs e)
     {
         if (!Regex.IsMatch(e.Text, "^[a-zA-Z]{0,10}$"))
         {
             e.Handled = true;
         }
     } 

I tried this regex but it doesn't work. I can write as many characters as I want without the validation stopping my entries. I would like to know why. In particular, if I remove the part that handles length, it works fine, but I need to handle length in my project

长话短说,e.Text 是部分问题,尤其是来自 TextCompositionEventArgs

当用户在该文本框中键入内容时,事件将启动, 将仅包含用户输入的值,而不包含之前输入的任何其他文本。为了检查用户之前输入的内容加上 新值,您需要连接两个单独的属性。

if (!Regex.IsMatch((e.Source as TextBox)?.Text + e.Text, "^[a-zA-Z]{0,10}$"))
{
   e.Handled = true;
} 

在上面的示例中,我使用了 e.Source,它是文本框本身及其当前文本(在此新值之前),加上 新值 。这就是为什么你只有一个长度的确切原因。

请注意,还有其他方法可以验证数据,但与此无关post并且会太长。