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
  • 4,920
  • 16
  • 58
  • 111

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,119
  • 1
  • 17
  • 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,515
  • 4
  • 21
  • 56