我想禁止在 WPF 应用程序的输入字段中输入所有表情符号(情感图标)。我实现它的方式是:
txtUserName.PreviewTextInput += LoginPreviewTextInput;
LoginPreviewTextInput 如下所示:
private void LoginPreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!InputValidator.IsValidInput(e.Text))
e.Handled = true;
}
InputValidator 的 IsValidInput 如下所示:
public class InputValidator
{
//These characters are allowed in the textbox
private static string pattern = @"^[\w\s,\.\(\)~!@\#\$%\^&\*-=\+\[\]\{\}:;'""<>\?\\|]*$";
public static bool IsValidInput(string previewedInput)
{
var matches = Regex.Matches(previewedInput, pattern);
if (matches.Count == 1)
{
return true;
}
return false;
}
}
奇怪的是,它适用于虚拟键盘中的所有 Emoji 图标,除了 Happy Emoji。它不起作用,因为一旦我在 Windows 虚拟键盘中输入此表情符号(它适用于所有其他表情符号),就不会调用 LoginPreviewTextInput。
快乐表情符号如下图所示:
当在文本框中输入快乐表情符号时,文本框如下所示:
快乐的表情符号已输入到文本框中。您可以看到,当文本框的文本属性为空时,甚至会显示一个水印。当我在 snoop 中查看文本框的 text 属性时,它确实是空的,而有界属性是 viewmodel 是空的(从未调用过 setter)。
同样,仅针对这个特定的表情符号(快乐的)发生。所有其他表情符号都进入 LoginPreviewTextInput 方法,不匹配正则表达式并被忽略。



