Wpf – How to find out where the focus is going in the WPF application

focuslost-focuslostfocuswpf

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

Best Answer

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