在鼠标事件中,我尝试创建TextBox,将其添加到Grid,选择all并聚焦键盘。但是无法让它发挥作用:
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();
}
我已尝试Keyboard.Focus(text);
和text.Focus();
。如果我这样做:
private void lostFocus(object sender, RoutedEventArgs e)
{
Keyboard.Focus(sender as TextBox);
e.Handled = true;
}
我得到了StackOverflowException,导致它在焦点后立即失去焦点。
也许有人可以帮我解决这个问题?
答案 0 :(得分:1)
我会回答:
text.LostKeyboardFocus += Text_LostKeyboardFocus;
和
private void Text_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)
{
var name = ((FrameworkElement)e.NewFocus).Name;
Console.Write(name);
}
帮助我发现我的ScrollViewer正在获得焦点,因此ScrollViewer的Focusable="False"
解决了这个问题。