1

I have a window with a TextBox and a Button. I want to always focus my TextBox, but allow the user to click the button. How can I do it?

I tried it by using a LostFocusEvent, that whould check who has the focus, and if it wasn't the Button it would focus the TextBox back, but I always get a System.StackOverflowException...

This what I was using:

    private void TextLostFocus(object sender, RoutedEventArgs e)
    {
      IInputElement focusedControl = FocusManager.GetFocusedElement(this);

      if (focusedControl != btn && focusedControl != txt)
      {
        txt.Focus();
      }
    }

Is there a way to do this?

alface
  • 79
  • 2
  • 10

4 Answers4

0

in the button click event you can give focus back to your text box like this.

textbox.focus();
C Smith
  • 222
  • 1
  • 6
0
Textbox.Select();

Focus is a lower level method used for custom controls. I would stick to select() or activate()

Brett Reinhard
  • 374
  • 2
  • 13
0
private void TextLostFocus(object sender, RoutedEventArgs e)
{
  ((TextBox) sender).Focus();
}
ByMedion
  • 21
  • 4
  • 2
    When posting a code sample, please explain why this will help the author with their original problem. – Patrick Aug 24 '17 at 11:32
0

you could use ActiveControl Property to set focus to your text box.

    this.ActiveControl = yourTextboxName; 
Ravi Kumar G N
  • 396
  • 1
  • 3
  • 11