Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I know there has been much discussion on this subject but I'm afraid I do not get it. I have a Parent UserControl to which I am adding a Child UserControl at runtime. The Child UserControl has a menu. The Menu items are not enabled until the Child UserControl has keyboard focus. The Child UserControl is added with the click event of a button.

How do I set the focus to the Child UserControl?

I have tried all sorts of variations of Focus() and KeyBoard.Focus to no avail. The focus remains on the clicked button of the Parent UserControl.

C#
class ParentUserControl
{
    public void ChangeContent(UIElement newContent)
    {
        var userControl = newContent as IBaseUserControl;
        if (userControl == null)
        {
            throw new NoNullAllowedException();
        }

        if (GridControl.Children.Count == 0)
        {
            GridControl.Children.Add(newContent);
            userControl.GetObservableCollection();
        }
        else
        {
            GridControl.IsHitTestVisible = false;
            var oldContent = GridControl.Children[0];

            EventHandler onAnimationCompletedHandler = delegate
            {
                GridControl.IsHitTestVisible = true;
                GridControl.Children.Remove(oldContent);
                userControl.GetObservableCollection();
            };

            FadeAnimation(newContent, oldContent, onAnimationCompletedHandler);
        }

        // None of these work
        //GridControl.Focus();
        //newContent.Focus();
        //Keyboard.Focus(newContent);
        Keyboard.Focus(GridControl);
    }

}
Posted
Updated 10-Jun-12 12:04pm
v3

1 solution

Set the newContent.Focus().... And or try some of these:

http://blogs.imeta.co.uk/jpanni/archive/2008/12/30/wpf-uielement.focus.aspx[^]

If the usercontrol xaml markup can be changed, make sure you set the Focusable property to true.

http://msdn.microsoft.com/en-us/library/system.windows.uielement.focusable.aspx[^]
 
Share this answer
 
Comments
Wbehning 10-Jun-12 18:45pm    
If you read my code, you will see that I tried that, it does not work.

// None of these work
//GridControl.Focus();
//newContent.Focus();
//Keyboard.Focus(newContent);
Keyboard.Focus(GridControl);
Wbehning 12-Jun-12 8:28am    
You were correct. The UserControl focusable property was false. Since all the UserControls inherit from BaseUserControl, all that needed to be done was modify the constructor

public BaseUserControl()
{
Focusable = true;
}

Then of course call newContent.Focus().
db7uk 12-Jun-12 8:32am    
cool, glad all is at one with the world.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900