Wpf – Focus Textbox using only XAML

focustextboxwpfxaml

I'm trying to set the keyboard focus to a textbox that is included in a stackpanel collapsed by default. When the stackpanel becomes visible i want the textbox to become, by default, focused.

I've tried this code:

<StackPanel Orientation="Vertical" FocusManager.FocusedElement="{Binding ElementName=TxtB}">
  <TextBox x:Name="TxtA" Text="A" />
  <TextBox x:Name="TxtB" Text="B" />
</StackPanel>

However, it didn't work. The type cursor showed up, but it wasn't blinking and didn't allow writing.

Is it possible to solve my problem using only XAML? Perhaps triggers?

Best Answer

Yes, as you said yourself, simple trigger seems to do the trick:

<StackPanel Orientation="Vertical">
    <StackPanel.Style>
       <Style TargetType="StackPanel">
          <Style.Triggers>
              <Trigger Property="Visibility" Value="Visible">
                  <Setter Property="FocusManager.FocusedElement" 
                          Value="{Binding ElementName=TxtA}" />
              </Trigger>
          </Style.Triggers>
       </Style>
    </StackPanel.Style>

    <TextBox x:Name="TxtA" Text="A" />
    <TextBox x:Name="TxtB" Text="B" />
</StackPanel>