【问题标题】:WPF UserControl GotFocusWPF 用户控件 GotFocus
【发布时间】:2016-09-27 06:46:48
【问题描述】:

我有一个包含多个组合框和按钮的用户控件。

在承载 UserControl 的窗口中,当 UserControl 获得焦点时,我需要更新一些属性。

我的问题是,每次当用户控件内的焦点发生变化时,都会在托管窗口中获得 GotFocus 事件。

是否有某种最佳实践可以确保我在托管窗口中只获得一个 GotFocused 事件?我的意思是,如果我单步执行 UserControl 内的控件,焦点始终在 UserControl 内,所以我不想要 GotFocused 事件。

【问题讨论】:

    标签: wpf user-controls


    【解决方案1】:

    这是我想出的解决方案:

    首先,这篇文章是我解决方案的关键:WPF UserControl detect LostFocus ignoring children

    还有Refer to active Window in WPF?

    使用这些帖子中的函数,我在我的 UserControl 中注册了 LostFocus 事件。

    private void UserControl_LostFocus(object sender, RoutedEventArgs e)
    {
      var focused_element = FocusManager.GetFocusedElement(Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive));
      var parent = (focused_element as FrameworkElement).TryFindParent<KeywordSelector>();
    
      if (parent != this) userControlHasFocus=false;
    }
    

    然后……

    private void UserControl_GotFocus(object sender, RoutedEventArgs e)
    {
      if (userControlHasFocus == true) e.Handled = true;
      else userControlHasFocus = true;
    }
    

    这样我就可以跟踪焦点。 userControlHasFocus 默认为 false。当 GotFocus() 第一次发生时,它是错误的,并且 GotFocus 事件不会停止冒泡。但是 userControlHasFocus 设置为 true,因为现在焦点在 UserControl 内部。

    每当焦点移动到另一个控件时,LostFocus 都会检查新控件的父控件是否是 UserControl。如果不是,它会将 userControlHasFocus 重置为 false。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多