Search code examples
c#wpfuser-controlstextbox

Set focus on TextBox in UserControl


In my program I have a user control that displays data on a window using a content presenter. I would like to simply set the cursor focus on a certain textBox in my window at startup.

Usually I would do this through the code-behind of the window, like this: textBox.Focus();

However, the textBox is defined in the user control, and doesn't seem to work the same way. So far I have tried the same method as above in the user control's code-behind.

Why doesn't this work? How do I set the focus if the textBox is defined in a user control?

What I have tried....:

User Control:

public UserControl()
{
    InitializeComponent();

    FocusManager.SetFocusedElement(this, textBox);
}

User Control:

public UserControl()
{
    InitializeComponent();

    textBox.Focusable = true;
    Keyboard.Focus(textBox);
}

Solution

  • Give this a try: FocusManager.SetFocusedElement

    FocusManager.SetFocusedElement(parentElement, textBox)
    

    or from the msdn website:

    textBox.Focusable = true;
    Keyboard.Focus(textBox);
    

    Note: You can't set focus in a constructor. If you are, UI Elements have not been created at that point. You should set focus during the Loaded event of your control.