【问题标题】:Programmatically sending keys to a textbox does not update its binding以编程方式将密钥发送到文本框不会更新其绑定
【发布时间】:2014-02-18 15:01:46
【问题描述】:

我在 WPF 桌面应用程序中使用第三方键盘控件(来自 DevComponents 的 DotNetBar,链接 here)在 TextBox 控件中输入文本。该应用程序是在 Windows 8 和 .NET 4.5 上开发的。

注意: Windows 平板电脑提示已尝试,但它有许多限制,使其难以使用。

键盘是一个 WindowsForms 控件,它被放置在一个 WindowsFormsHost 中。 由于此键盘使用的 WindowsForms SendKeys 方法在 WPF 中无法正常工作(正如许多关于 SO 的文章中提到的那样),我使用 InputManager 以编程方式将键发送到文本框,如下所示:

    private void _keyboardControl_SendingKey(object sender, KeyboardKeyCancelEventArgs e)
    {
        // to prevent SendKeys to happen.
        e.Cancel = true;

        if (string.IsNullOrEmpty(e.Key))
        {
            return;
        }

        // A special key is a key like "Enter", "Backspace", "Left arrow", ...
        if (IsSpecialKey(e.Key))
        {
            var keyEventArgs = new KeyEventArgs(
               System.Windows.Input.Keyboard.PrimaryDevice,
                System.Windows.Input.Keyboard.PrimaryDevice.ActiveSource,
               0,
               GetKeyValueFromStringCode(e.Key)) { RoutedEvent = Keyboard.KeyDownEvent };
            InputManager.Current.ProcessInput(keyEventArgs);
        }
        // "Normal" keys, like a, b, C, (, 1, ....
        else
        {
           var textCompositionEventArgs = new TextCompositionEventArgs(
           System.Windows.Input.Keyboard.PrimaryDevice,
            new TextComposition(InputManager.Current,
                System.Windows.Input.Keyboard.FocusedElement,
                e.Key)) { RoutedEvent = Keyboard.TextInputEvent };

            InputManager.Current.ProcessInput(textCompositionEventArgs);
        }
    }

这有效地将右键放入目标 WPF 文本框中,该文本框在显示第三方键盘之前具有焦点。 文本框 Text 属性已绑定到 ViewModel 属性。问题是当以编程方式输入键时,对文本框所做的更新不会通过绑定传播。 如果我使用自己的物理键盘在同一个文本框中键入,则绑定会正确更新。

对此的任何指导将不胜感激。到这里花了一段时间,如果我正在尝试的东西是不可能的,那就太糟糕了。谢谢!

【问题讨论】:

    标签: c# wpf binding textbox keyboard


    【解决方案1】:

    Binding.UpdateSourceTriggerTextBox 的文本 DP 默认值为LostFocus。因此,在失去对 textBox 的焦点之前,不会更新绑定源。

    您需要将其设置为PropertyChanged,这样无论何时 Text 属性更改,它都会更新为源绑定。

    <TextBox Text="{Binding PropertyName, UpdateSourceTrigger=PropertyChanged}"/>
    

    【讨论】:

    • 感谢 Rohit 这么快的回答。非常感激!我猜在使用物理键盘打字时,焦点会丢失,但文本仍在发送到文本框。我明确地做了一个“Focusable=fasle;”在我的 WindowsFormsHost 中,以便 Keyboard.FocusedElement 和 Keyboard.PrimaryDevice.ActiveSource 发送我的 TextBox 中的键。否则这是行不通的,宁愿不必显式引用我的 TextBox 控件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 2019-12-04
    • 1970-01-01
    • 2017-04-04
    • 1970-01-01
    • 2015-05-16
    相关资源
    最近更新 更多