WPF Reset Focus on Button Click WPF Reset Focus on Button Click wpf wpf

WPF Reset Focus on Button Click


I encountered a similar issue. I need to unfocus a textbox when enter is pressed. I end up with this code:

var scope = FocusManager.GetFocusScope(elem); // elem is the UIElement to unfocusFocusManager.SetFocusedElement(scope, null); // remove logical focusKeyboard.ClearFocus(); // remove keyboard focus

I think it is cleaner than creating dummy controls and it is reusable. I'm not confident with this solution though. But it seems work well.


The problem is that the toolbar places your button in a different FocusManager.FocusScope. That means that both the Button and the TextBox can receive logical focus at the same time, each in its own scope. This is normally a good thing, since you usually don't want to lose focus in your main window area when you select menu items and ToolBar buttons, but in your case it is preventing what you are doing from working.

Although you could override the FocusManager.IsFocusScope property on the toolbar and get the effect you want, this is probably not the best plan since it would make all the other toolbar buttons also steal focus from your main window area.

Instead you could use one of several easy solutions:

  • Put your button outside the Toolbar
  • Add a Focusable="true" control to your main window area and focus it when the button is clicked
  • Manually force the update by calling textBox.GetBindingExpression(TextBox.TextProperty).UpdateSource()
  • Temporarily set Focusable="true" on a control in the main window, set focus to it, then immediately set Focusable="false" again


I had an issue leaving a calendar and needing to click a button twice (WPF, .Net 5.0), I tried some of the suggested solutions above but no luck, however this worked - quoted from someone on the Microsoft site:

"My solution to this problem was to insert into the main form, but it's probably overkill."

protected override void OnPreviewMouseUp(MouseButtonEventArgs e){  base.OnPreviewMouseUp(e);  if (Mouse.Captured is Calendar || Mouse.Captured is System.Windows.Controls.Primitives.CalendarItem)  {    Mouse.Capture(null);  }}