3

Based on this link: Set the focus on a textbox in xaml wpf , Focus can be set by setting FocusManager at the StackPanel and specifying the elementName. I did tried out and it works. I'm wondering what if I have only one textbox in my XAML and StackPanel is unnecessary?

Is there any other simple way to set focus given the scenario I only have one textbox?

I've also tried the second answer in the above link but doesn't work:

<TextBox Text="{Binding MyText}" 
    FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>
Community
  • 1
  • 1
SuicideSheep
  • 5,260
  • 19
  • 64
  • 117

2 Answers2

1

I've done this in the past by putting the focus in the header - in this case a user control, though should be the same for a window)

<UserControl .....
FocusManager.FocusedElement="{Binding ElementName=TextBoxName}">
NDJ
  • 5,189
  • 1
  • 18
  • 27
0
<TextBox Text="{Binding MyText}" 
       FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource AncestorType=TextBox}}"/>

or

<TextBox x:Name="MyTBox" Text="{Binding MyText}" 
       FocusManager.FocusedElement="{Binding ElementName=MyTBox}"/>

This will works for your case.

Sankarann
  • 2,625
  • 4
  • 22
  • 59