WPF:无法设置焦点 [英] WPF: Cannot set focus
问题描述
UserControl_PreviewTextInput被登记在该用户控件的处理程序包含该文本框如果这个事务。
私人无效UserControl_PreviewTextInput(对象发件人,TextCompositionEventArgs e)
{
CodeLineControl el = new CodeLineControl();
container.Children.Insert(idx + 1,el);
el.innerTextBox.Focus();
$ p CodeLineControl是这样定义的(简体):
< UserControl ..>
< DockPanel Name =codelineBackground =AntiqueWhite>
< TextBox Name =innerTextBox/>
< / DockPanel>
< / UserControl>
Focus对Iam没有一些限制吗?我不允许将Focus()从PreviewTextInput处理程序中的TextBox移开?我不能将焦点设置在新创建的元素?
解决方案 创建一个延迟后呼吁关注该文本框一个DispatcherTimer
I want that from the PreviewTextInput handler a new control is created and focus is set to it. But even after calling Focus() on the new control, the cursor is still in the old textbox.
The handler UserControl_PreviewTextInput is registered on the UserControl which contains this textbox if this matters.
private void UserControl_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
CodeLineControl el = new CodeLineControl();
container.Children.Insert(idx+1, el);
el.innerTextBox.Focus();
}
CodeLineControl is defined like that(simplified):
<UserControl ..>
<DockPanel Name="codeline" Background="AntiqueWhite" >
<TextBox Name="innerTextBox"/>
</DockPanel>
</UserControl>
Are there some limitations on Focus() that Iam not awre about? Am I not allowed to move Focus() away from a TextBox from a PreviewTextInput handler? Can't I set the focus on newly created elements?
解决方案 Create a DispatcherTimer that calls Focus on that textbox after a delay
这篇关于WPF:无法设置焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!