WPF TextBox事件

时间:2014-06-06 23:19:24

标签: c# wpf

我有一个文本框,我需要用户只输入西里尔字母。用户不能输入数字和特殊字符(空格除外)和拉丁字符!变量“l”的值我将自己设定。

如何让KeyDown事件执行此操作?

在WindowsForms中,我这样做:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{

    char l = e.KeyChar;
    if ((l < 'А' || l > 'я') && l != '\b' )
    {
       e.Handled = true;
    }
}

1 个答案:

答案 0 :(得分:1)

我发现的最简单的方法是利用OnPreviewTextInput事件:

标记:

<TextBox PreviewTextInput="UIElement_OnPreviewTextInput" />

处理程序:

private void UIElement_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    bool isCyrillic = Regex.IsMatch(e.Text, @"\p{IsCyrillic}");
    e.Handled = !isCyrillic;
}