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

591 Views Asked by At

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

2

There are 2 best solutions below

0
emoacht On

WPF's UserControl inherits FrameworkElement which has FrameworkElement.OnGotFocus method. So you can use it as follows:

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

    FocusManager.SetFocusedElement(Window.GetWindow(this), this.TextBoxToPutFocusOn);
}
0
Larry On

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}">