Reputation: 377
On mouse event I'm trying to create TextBox, add it to Grid, select all and focus keyboard. But can't get it working:
private void timeCodeEdit(object sender, MouseEventArgs e)
{
Grid grid = (Grid) ((Label) sender).Parent;
TextBox text = new TextBox();
text.Margin = new Thickness(0, 0, 75, 0);
text.Text = "aaaa";
grid.Children.Add(text);
text.LostFocus += lostFocus;
Keyboard.Focus(text);
text.SelectAll();
}
I've tried Keyboard.Focus(text);
and text.Focus();
. And if I do this:
private void lostFocus(object sender, RoutedEventArgs e)
{
Keyboard.Focus(sender as TextBox);
e.Handled = true;
}
I'm getting StackOverflowException, cause it lost focus right after focus.
Maybe someone can help me about this?
Upvotes: 2
Views: 284
Reputation: 377
I'll post answer:
text.LostKeyboardFocus += Text_LostKeyboardFocus;
and:
private void Text_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var name = ((FrameworkElement)e.NewFocus).Name;
Console.Write(name);
}
Helped me find out that my ScrollViewer is getting focus, so Focusable="False"
for ScrollViewer solved the problem.
Upvotes: 1