views:

428

answers:

2

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  A: 

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

Mike Blandford
codymanix
I think it gets rendered asynchronously in a separate thread and you can't focus on it until that is complete. Or, it could be that after a new control is added, WPF changes the focus itself. Perhaps the LostFocus event is fired at some point? You could write a logfile to see what controls are getting/losing focus. http://www.julmar.com/blog/mark/PermaLink,guid,6e4769e5-a0b3-47b2-a142-6dfefd0c028e.aspx
Mike Blandford
+7  A: 

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.

Sergey Aldoukhov
great solution! +1
Dabblernl