Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

417
Views
How to set keyboard focus to a textbox inside a user control in WPF?

When I open the window MyWindow, I want to have the cursor of my keyboard pointing to the textbox contained in a user control that is contained in the window.

Usually, you would set FocusManager.FocusedElement={Binding ElementName=TextBoxToPutFocusOn}.

But here, my constraint is that the textbox is inside a user control that is inside my window.

How can my window set focus to this textbox?

To illustrate, here are my 2 files:

MyWindow.xaml

<Window
xmlns:wpf="clr-namespace:MyWPFNamespace">
    <StackPanel>
        <TextBlock>Sample text</TextBlock>
        <wpf:SpecialTextBox/>
    </StackPanel>
</Window>

SpecialTextBox.xaml

<UserControl
    x:Class="MyWPFNamespace.SpecialTextBox"
    x:Name="SpecialName">
    <TextBox
        x:Name="TextBoxToPutFocusOn" />
</UserControl>

Thank you

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

WPF's UserControl inherits FrameworkElement which has FrameworkElement.OnGotFocus method. So you can use it as follows (in C#):

protected override void OnGotFocus(RoutedEventArgs e)
{
    base.OnGotFocus(e);

    FocusManager.SetFocusedElement(Window.GetWindow(this), this.TextBoxToPutFocusOn);
}
over 4 years ago · Santiago Trujillo Report

0

I did it by setting the following property in the User Control:

<UserControl
    x:Class="MyWPFNamespace.SpecialTextBox"
    x:Name="SpecialName"
    FocusManager.GotFocus="MyTextBox_OnGotFocus">'

And in the code behind:

Private Sub TextBoxWithHint_OnGotFocus(sender As Object, e As RoutedEventArgs)
    MyTextBox.Focus()
End Sub

Finally, in MainWindow.xaml:

<Window
    FocusManager.FocusedElement="{Binding SpecialName}">
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!