WPF UserControl GotFocus

时间:2016-05-29 10:19:49

标签: wpf user-controls

我有一个包含几个ComboBox和Buttons的UserControl。

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

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

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

1 个答案:

答案 0 :(得分: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。

相关问题