【问题标题】:IME issue in Textbox文本框中的 IME 问题
【发布时间】:2018-04-13 00:02:44
【问题描述】:

我的 wpf 应用程序中有一个文本框。我通过 textchanged 事件中的代码将 maxLength 设置为 10。如果我输入英文字符,它的工作完美。但是,如果我通过 IME 将语言更改为平假名(日语),则会发生以下问题。

当我输入第 11 个字符时,文本框会自动将前 10 个字符附加到自身,这意味着 21 个字符(10 + 10 + 最后输入的字符)。

调试时,textchanged 事件执行多次。

提前致谢。

内存

【问题讨论】:

  • 你能告诉我们你的代码/到目前为止你做了什么吗?

标签: c# wpf


【解决方案1】:

更改 textchanged 事件中的文本将再次递归调用 textchanged 事件。
这就是您在调试中看到的循环。

解决方案是在更新值时删除 textchange 处理,然后重新添加。

    private void MyTextbox_OnTextChanged(object sender, TextChangedEventArgs e)
    {
        // Act on the 11th character
        if (MyTextbox.Text.Length != 11)
            return;

        // Remove handling of text changed event so we can update without recursive calls
        MyTextbox.TextChanged -= MyTextbox_OnTextChanged;

        // Update textbox value - example based on your question
        var valueWithoutNewCharacter = MyTextbox.Text.Substring(0, 10 - 1); // strings are 0 based
        MyTextbox.Text = valueWithoutNewCharacter + valueWithoutNewCharacter + MyTextbox.Text.Substring(10, 1);

        // Re-add the handling of the text changed event
        MyTextbox.TextChanged += MyTextbox_OnTextChanged;
    }

【讨论】:

  • 感谢您的回复...实际上我的文本框共有 3 行。每行的最大长度为 10。
  • 我测试了这段代码。实际上我只想要一行中的 10 个字符。在您的代码中,您正在解决我得到的问题 MyTextbox.Text = valueWithoutNewCharacter + valueWithoutNewCharacter + MyTextbox.Text.Substring(10, 1);.
猜你喜欢
  • 2011-04-23
  • 1970-01-01
  • 2021-08-21
  • 2011-08-05
  • 2016-03-28
  • 1970-01-01
  • 1970-01-01
  • 2011-03-18
相关资源
最近更新 更多