A memorandum to unfocus the TextBox

less than 1 minute read

I was a little addicted to it when implementing processing such as releasing the focus when the enter key was pressed, so I will write it down.
It would be nice if the control had a control.UnFocus ()` `like method, but unfortunately there was no such method. The first thing that comes to mind to implement this is to useKeyboard.ClearFocus () , which doesn't call the control LostFocus`.
So what to do is simple.
Just focus on another control.
However, it is not personally smart to write a process that focuses on a specific control for each program, so I will generalize it.
A code example is shown below.

Sample.cs


//Defocus the control
public void BreakFocus(Control control){
   DependencyObject ancestor = control.Parent; 
   while (ancestor != null)
   {
      //Can you focus
      if (ancestor is UIElement element && element.Focusable)
      {
            element.Focus(); //Focus
            break;
      }
      ancestor = VisualTreeHelper.GetParent(ancestor);
   }
}

It’s very simple. All you have to do is go back and guess until you find a control that you can focus on.
You have now implemented control unfocus.