How do I know where the focus is in my WPF application?

I have a search screen in my WPF application. The screen is implemented as a UserControl in a TabItem TabControl. When the user switches to the Search tab, I want the focus to move to one specific field.

So, I added the Loaded event handler to the UserControl tag in Xaml, and I called the Focus method for the control that I want to have initial focus in the Loaded event handler. This worked fine until I updated the Telerik management library that I use today. Now, when I switch to the Search tab, the focus is NOT in the field that I want to have, but I can’t tell which control has focus.

The field I want to focus on already has GotFocus and LostFocus event handlers for other reasons. I remembered that in Win Forms, the arguments to the LostFocus event handler suggest which control will receive the focus. So I set a breakpoint in the LostFocus handler and found that the arguments to the LostFocus event handler in WPF do not include this information.

How can I determine where the focus goes without putting GotFocus handlers on each control in UserControl?

Tony

+6
source share
2 answers

You can try to set a breakpoint on the LostKeyboardFocus Attached event instead of the LostFocus event. It uses the KeyboardFocusChangedEventArgs Class, which has properties that show which element had focus and where the focus is.

 private void textBox1_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) { textBox1.Text = ((FrameworkElement)e.NewFocus).Name ; } 
+5
source

Try pressing the Tab key and see if it helps you find the control in focus.

You can also use Snoop as suggested in this Q / A: Any tips on debugging focus in WPF?

To begin, Snoop shows the current focused item and the current FocusScope in the status bar.

You can get it to show you all the GotFocus and LostFocus events:

 1. Run your app. 2. Run Snoop. 3. Choose your app in the dropdown. 4. Click the binoculars ("Snoop") button. 5. On the right pane, click the Events tab. 6. Click to bring down the dropdown. 7. Scroll down to the Keyboard section and check GotKeyboardFocus, LostKeyboardFocus, and optionally the PreviewXXX events. 8. Now do what you need to do to manipulate focus and watch the Snoop window. 

Similarly, you can track FocusManager events the same way.

+8
source

Source: https://habr.com/ru/post/912002/


All Articles