【发布时间】:2020-10-01 07:04:51
【问题描述】:
我想做一个花哨的无效字符检测,就像我们在一些在线网站或移动应用程序中看到的那样。我使用 WPF (.NET Framework) 和 C# 代码。
下面是我的textbox1(用户输入)和textbox2(无效字符检测器)的 XAML 代码。
请注意,我使用的是 Material Design 主题。
<StackPanel VerticalAlignment="Center" Margin="10,20,10,30">
<TextBox Name="CreatedSQLDatabase"
BorderBrush="Black"
materialDesign:HintAssist.Hint="Add New Database Name"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
Margin="0,0,0,0"
FontFamily="Champagne & Limousines"
FontSize="12"
MaxLength="25"
KeyDown="OnKeyDownHandler"/>
</StackPanel>
<TextBox Name="InvalidCharacterDetection"
materialDesign:HintAssist.Hint="Invalid character"
Style="{StaticResource MaterialDesignFloatingHintTextBox}"
Margin="10,100,10,40"
FontFamily="Champagne & Limousines"
FontSize="12"
MaxLength="25"
IsReadOnly="True"/>
以下是无效字符事件处理程序检测器的 C# 代码:
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
var regex = new Regex(@"[^a-zA-Z0-9-()/\s\p{IsGreekandCoptic}]");
if (regex.IsMatch(e.Key.ToString()))
{
InvalidCharacterDetection.Text = "You Entered an invalid character";
CreatedSQLDatabase.Foreground = Brushes.Red;
}
else if (String.IsNullOrEmpty(CreatedSQLDatabase.Text))
{
InvalidCharacterDetection.Text = "Database name cannot be empty";
}
else if (CreatedSQLDatabase.Text.Length > 25)
{
InvalidCharacterDetection.Text = "Database name cannot exceed 25 characters";
}
}
输出不正确(没有应用任何正则表达式):
如何使KeyEvent 处理程序捕获if 语句并对textbox1 的颜色和textbox2 中出现的消息进行适当的更改?
如果关于此问题还有任何其他重复问题,请在 cmets 中通知我。到目前为止,我发现了以下问题:
【问题讨论】:
-
我认为你应该试试 PreviewTextInput。 stackoverflow.com/questions/38313281/… 如果这不起作用,请在此应用程序之外尝试您的正则表达式并检查是否正确。