【发布时间】: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