5

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);
}
Eric after dark
  • 1,768
  • 4
  • 31
  • 79

3 Answers3

5

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.

JTFRage
  • 387
  • 7
  • 20
3

A little bit late but what it really worked for my was

public UserControl()
    {
        InitializeComponent();

        Dispatcher.BeginInvoke(new System.Action(() => { Keyboard.Focus(TextBox); }),
                               System.Windows.Threading.DispatcherPriority.Loaded);
    }
Ieskudero
  • 31
  • 2
2

You can try setting the focus in the Loaded or Initialized event of the User control. Eg:

private void MyWpfControl_Load(object sender, EventArgs e)
{
    textBox.Focusable = true;
    Keyboard.Focus(textBox);
}

Info: Loaded event or Initialized event

MikeSmithDev
  • 15,731
  • 4
  • 58
  • 89
Loetn
  • 3,832
  • 25
  • 41