user10034891
user10034891

Reputation:

How to initialize and set focus to textbox in a button click in WPF

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.

Upvotes: 0

Views: 753

Answers (2)

Shakaib Akhtar
Shakaib Akhtar

Reputation: 371

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();

Upvotes: 1

jegtugado
jegtugado

Reputation: 5141

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();
}

Upvotes: 1

Related Questions