2017-02-10 53 views
2

在鼠标事件我试图创建TextBox,将其添加到网格,选择所有和焦点键盘。但不能得到它的工作:WPF麻烦获取TextBox集中

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

尝试'FocusManager.SetFocusedElement(parentElement,txtBoxName)' – Gopichandar

+0

我试过了,但它没有帮助 – Tom1410

+0

你的代码对我来说工作正常;该文本框是专注,我可以直接输入。我尝试了'MouseEnter'和'MouseLeftButtonDown'事件。你使用的是什么.NET框架? – AjS

回答

1

我会后回答:

text.LostKeyboardFocus += Text_LostKeyboardFocus; 

和:

private void Text_LostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e) 
{ 
    var name = ((FrameworkElement)e.NewFocus).Name; 
    Console.Write(name); 
} 

帮我找到了我的ScrollViewer越来越专注,所以Focusable="False"为ScrollViewer中解决了这个问题。