我有一个应用程序,必须在某些UIElements获得焦点(TextBox,PasswordBox等)时打开屏幕键盘。我在MainWindow上使用GotKeyboardFocus和LostKeyboardFocus来实现这个目标:
this.GotKeyboardFocus += AutoKeyboard.GotKeyboardFocus;
this.LostKeyboardFocus += AutoKeyboard.LostKeyboardFocus;
一切都很好,除非我打开一个包含自己的TextBoxes的新窗口。显然,由于它们不是MainWindows routedEvent的一部分,因此它们不会触发键盘焦点事件。有没有办法可以让所有子窗口从MainWindow继承GotKeyboardFocus或让它将键盘焦点事件传递回其父窗口?
答案 0 :(得分:4)
我建议使用 EventManager 来注册所选事件的全局(应用程序范围)处理程序。这是一个例子:
public partial class App : Application
{
public App()
{
EventManager.RegisterClassHandler(
typeof (UIElement),
UIElement.GotKeyboardFocusEvent,
new RoutedEventHandler(GotKeyboardFocusEventHandler));
EventManager.RegisterClassHandler(
typeof (UIElement),
UIElement.LostKeyboardFocusEvent,
new RoutedEventHandler(LostKeyboardFocusEventHandler));
}
private void GotKeyboardFocusEventHandler(object sender, RoutedEventArgs routedEventArgs)
{
...
}
private void LostKeyboardFocusEventHandler(object sender, RoutedEventArgs routedEventArgs)
{
...
}
}