如何在WPF C#中的Keydown事件上输入字符

问题描述

我在Visual Studio中使用WPF C# 我想防止用户可以输入阿拉伯字符,波斯字符

就像当用户键盘上输入此值时→“ي”将其更改为“ی”

我的意思是这样的: 当用户按下按钮以在键盘上键入“ A”时,我想更改此字符,请先检查是否将“ A”更改为“ B”

我在Windows窗体应用程序中做到了,但是该代码在WPF中不起作用

我在Windows中的代码来自:

if (e.KeyChar.ToString() == "ي")
            {
                e.KeyChar = Convert.tochar("ی");
            }

我在WPF中的代码

 if (e.Key.ToString() == "ي")
    {
         e.Key.ToString("ی");
     }

这些代码在WPF中不起作用

请帮助

解决方法

在WPF中有所不同。

这可以使用英文键盘工作。不知道它是否适用于阿拉伯语,因为插入字符的规则可能有所不同。

您可以尝试处理TextBox的 PreviewTextInput 事件。

XAML

<TextBox PreviewTextInput="TextBox_OnTextInput" ...  

代码

        private void TextBox_OnTextInput(object sender,TextCompositionEventArgs e)
        {
            var box = (sender as TextBox);
            var text = box.Text;
            var caret = box.CaretIndex;

            if (e.TextComposition.Text == "ي")
            {
                var newValue = "ی";

                //Update the TextBox' text..
                box.Text = text.Insert(caret,newValue);
                //..move the caret accordingly..
                box.CaretIndex = caret + newValue.Length;
                //..and make sure the keystroke isn't handled again by the TextBox itself:
                e.Handled = true;
            }
        }