Larry
Larry

Reputation: 37

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

Upvotes: 2

Views: 866

Answers (2)

emoacht
emoacht

Reputation: 3601

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);
}

Upvotes: 1

Larry
Larry

Reputation: 37

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

Upvotes: 0

Related Questions