以编程方式将密钥发送到文本框不会更新其绑定

时间:2014-01-27 16:44:56

标签: c# wpf binding textbox keyboard

我在WPF桌面应用程序中使用ThirdParty键盘控件(来自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文本框中,该文本框在显示ThirdParty键盘之前具有焦点。 文本框Text属性已绑定到ViewModel属性。问题是,在以编程方式输入密钥时,不会通过绑定传播对文本框所做的更新。 如果我使用自己的物理键盘在同一文本框中键入,则绑定会正确更新。

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

1 个答案:

答案 0 :(得分:2)

默认情况下, TextBox

Binding.UpdateSourceTrigger值为LostFocus。因此,在对textBox失去焦点之前,不会更新绑定源。

您需要将其设置为PropertyChanged,以便每当Text属性更改时,它都会更新为源绑定。

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