2

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

Larry
  • 27
  • 2
  • 1
    try UIElement.Focus() – martinrhan Feb 06 '22 at 02:07
  • 1
    Why don't you override OnGotFocus in the code behind of the UserControl and call FocusManager.SetFocusedElement method? – emoacht Feb 06 '22 at 04:09
  • Thank you @emoacht. I am using WPF and not Windows Forms. It seems OnGotFocus can be overriden if it is a WinForm control, right? – Larry Feb 06 '22 at 14:56
  • In WPF, I did it by setting the following property in the User Control: `FocusManager.GotFocus="MyTextBox_OnGotFocus"` And in the code behind: `Private Sub TextBoxWithHint_OnGotFocus(sender As Object, e As RoutedEventArgs) MyTextBox.Focus() End Sub` – Larry Feb 06 '22 at 15:04

2 Answers2

1

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);
}
emoacht
  • 2,764
  • 1
  • 13
  • 24
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}">
Larry
  • 27
  • 2