在鼠标事件上,我正在尝试创建 TextBox,将其添加到 Grid,全选并聚焦键盘。但无法让它工作:
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,导致它在获得焦点后立即失去焦点。
也许有人可以帮我解决这个问题?
最佳答案
我会发布答案:
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"
解决了这个问题。
关于c# - WPF 无法聚焦 TextBox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42153074/