0

I have a UserControl that contains several ComboBoxes and Buttons.

In the window that hosts the UserControl I need to update some properties when the UserControl gets the focus.

My problem is, that every time, when the focus inside the user control changes, that get a GotFocus event in the hosting windows.

Is there some kind of best practice to make sure, that I only get one GotFocused event in the hosting window? I mean, if I step through controls inside the UserControl the focus is always inside the UserControl, so I don't want a GotFocused event.

be_mi
  • 529
  • 6
  • 21

1 Answers1

1

This is the solution I came up to:

First of all this post was the key for my solution: WPF UserControl detect LostFocus ignoring children .

And Refer to active Window in WPF? .

Using the functions in these posts I registered the LostFocus event in my UserControl.

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;
}

And then ...

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

This way I keep track of the focus. userControlHasFocus is false be default. When the GotFocus() happens for the first time it's false and the GotFocus event is not stopped form bubbling up. But userControlHasFocus gets set to true, because now the focus is inside the UserControl.

Whenever the focus moves to another control, LostFocus checks if the new controls parent is the UserControl. If not, it resets the userControlHasFocus to false.

Community
  • 1
  • 1
be_mi
  • 529
  • 6
  • 21