How do I find out where the focus is going in my WPF application?

本小妞迷上赌 提交于 2019-12-07 00:08:58

问题


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

So I added a Loaded event handler to the UserControl tag in the Xaml and I called the Focus method of the control I want to have the initial focus in the Loaded event handler. This worked great until I upgraded the Telerik control library I'm using today. Now, when I switch to the Search tab, the focus is NOT in the field I want to have it, but I can't tell what control does have the focus.

The field I want to have focus already has GotFocus & LostFocus event handlers for other reasons. I remembered that in Win Forms, the LostFocus event handler arguments tell you which control is going to get the focus. So I put a breakpoint in my LostFocus handler & discovered that the arguments to the LostFocus event handler in WPF don't include that information.

How can I figure out where the focus is going without putting GotFocus handlers on every control in my UserControl?

Tony


回答1:


You can try putting your breakpoint on the LostKeyboardFocus Attached Event instead of the LostFocus Event. It uses the KeyboardFocusChangedEventArgs Class which does have properties that show which element had focus and where the focus is going.

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



回答2:


Try to press 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 issues in WPF?

For starters, Snoop shows the current focused element 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 the FocusManager events the same way.



来源:https://stackoverflow.com/questions/9935386/how-do-i-find-out-where-the-focus-is-going-in-my-wpf-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!