【问题标题】:GotKeyboardFocus event from child to parent windowGotKeyboardFocus 事件从子窗口到父窗口
【发布时间】:2014-04-15 10:31:33
【问题描述】:

我有一个应用程序,当某些 UIElements 获得焦点(TextBox、PasswordBox 等)时,它必须打开屏幕键盘。我在 MainWindow 上使用 GotKeyboardFocus 和 LostKeyboardFocus 来实现这一点:

this.GotKeyboardFocus += AutoKeyboard.GotKeyboardFocus;
this.LostKeyboardFocus += AutoKeyboard.LostKeyboardFocus;

一切都很好,除非我打开一个包含自己的文本框的新窗口。显然,由于它们不是 MainWindows routedEvent 的一部分,它们不会触发键盘焦点事件。有没有办法让所有子窗口从 MainWindow 继承 GotKeyboardFocus 或让它将键盘焦点事件传回其父窗口?

【问题讨论】:

  • 创建子窗口的时候,为什么不呢:childWindow.GotKeyboardFocus += AutoKeyboard.GotKeyboardFocus;
  • 我已经完成了大部分工作,但有两个主要问题。首先是整个应用程序中有很多子窗口。将这条线添加到它们都是可能的,如果这是唯一的解决方案,我会这样做。更大的问题是我们的一些窗口使用来自其他库的用户控件。其中一些控件会打开它们自己的私有窗口,我们不允许更改这些库中的代码。

标签: c# wpf events


【解决方案1】:

我建议使用 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)
    {
       ...
    }
}

【讨论】:

  • 优秀的解决方案!我不敢相信我在几个小时的搜索中没有遇到这个。你为我节省了很多工作。每次创建新窗口时,我都准备放弃并添加事件。谢谢。
猜你喜欢
  • 2012-10-31
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
相关资源
最近更新 更多