Jerry Nixon on Windows: Setting the Focus back to the WPF/UI

Jerry Nixon on Windows

Tuesday, July 19, 2011

Setting the Focus back to the WPF/UI

This is perhaps the single-most important secret in WPF. After you manipulate the UI through code behind, it is important to re-establish the focus back to the UI elements. This is important to maintain the user's context, but also to refresh the state of routed commands and the buttons that they control. You can do this manually using SomeControl.Focus() but you do not always know what control deserves the focus. The WPF runtime knows. And this is how you tell it to set the focus for you – and to the correct element.

MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));