'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
Solution 1:[1]
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);
}
Solution 2:[2]
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}">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | emoacht |
| Solution 2 | Larry |
