0

I have button click event where i initialize a new TextBox and try to get focus on it, its not working.(I guess the TextBox isnt loaded yet so not getting focused)

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        TextBox box = new TextBox();
        box.Width = 200;
        box.Height = 30;
        box.Focusable = true;
        box.Focus();
        this.stackPanel.Children.Add(box);
    }

How can i achieve focus?

In Xaml i have a StackPanel and a Button

Thanks in advance.

  • Possible duplicate of [how to put focus on TextBox when the form load?](https://stackoverflow.com/questions/6597196/how-to-put-focus-on-textbox-when-the-form-load) – Carlo Zanocco Sep 11 '18 at 06:36

2 Answers2

1

You need to call .Focus() after adding it to the stack panel.

private void Button_Click(object sender, RoutedEventArgs e)
{
    TextBox box = new TextBox();
    box.Width = 200;
    box.Height = 30;
    box.Focusable = true;

    this.stackPanel.Children.Add(box);
    box.Focus();
}
jegtugado
  • 5,081
  • 1
  • 12
  • 35
1

I think u should try this,,, first add the textbox to panel then focus on it.

TextBox box = new TextBox();
box.Width = 200;
box.Height = 30;
box.Focusable = true;
this.stackPanel.Children.Add(box);
box.Focus();
Eldho
  • 7,795
  • 5
  • 40
  • 77
Shakaib Akhtar
  • 381
  • 3
  • 10