Reputation:
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
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
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