WPF:无法设置焦点 [英] WPF: Cannot set focus

查看:367
本文介绍了WPF:无法设置焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从PreviewTextInput处理程序中创建一个新的控件,并将焦点设置为它。但即使在新控件上调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆