c# - WPF 无法聚焦 TextBox

标签 c# wpf

在鼠标事件上,我正在尝试创建 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/

相关文章:

c# - 如何禁用 FlowLayoutPanel 中的水平滚动条?

c# - VB.NET 'Char' 值无法转换为 'Integer'

C# Datagrid(不是datagridview): how to sort a column of numbers since all values are stored as Text?

wpf - 当没有绑定(bind)元素时使默认可见性折叠

WPF - 从绑定(bind)路径获取属性值

c# - 有什么方法可以使用 Wpf (C#) 更改 Web 浏览器的上下文菜单

c# - 如何缩小字符串并在以后找到原始字符串

c# - 从 Azure SAS URI 创建 BlobContainerClient

c# - nhibernate 一对一映射和非空 ="false"?

c# - 指定三次贝塞尔曲线中的张力