WPF: Cannot set focus

烈酒焚心 提交于 2020-01-01 05:34:06

问题


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?


回答1:


Create a DispatcherTimer that calls Focus on that textbox after a delay




回答2:


This is the extension method I use for instead of Focus:

    public static void BackgroundFocus(this UIElement el)
    {
        Action a = () => el.Focus();
        el.Dispatcher.BeginInvoke(DispatcherPriority.Background, a);
    }

No need to create a timer.



来源:https://stackoverflow.com/questions/1395887/wpf-cannot-set-focus

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!