Wpf setting keyboard focus on textbox using xaml

wpfxaml

in a wpf project afer the window loads i am trying to set focus on a textbox using the xaml.

My textbox is inside a grid.Here is the code i used

<Grid Name="gvLoginPage"
      Margin="0,30,0,0"
      FocusManager.FocusedElement="{Binding ElementName=txtUserName}">
 <TextBox Name="txtUserName"
          Focusable="True"
          ToolTip="Please enter your user name"
          Width="300"
          Height="22"
          VerticalContentAlignment="Top"
          TextWrapping="Wrap"
          Grid.Row="0"
          Grid.Column="1"
          BorderBrush="Black">
<Grid>

this code is setting the focus but cursor is not blinking and i can not type anything.

Then i came across this question Get and restore WPF keyboard focus where he explains that there are two types of focus one is logical focus and other is keyboard focus and FocusManager.FocusedElement sets logical focus not keyboard focus.so i can not get blinking cursor.

using code behind i can solve this using

Keyboard.Focus(txtUserName);

But i want to keep my code behind as less as possible.so please somebody help me to set keyboard focus on textbox using xaml.

Best Answer

According to @olitee's comment i used my gridview's IsVisible property to fire a DataTrigger and set the Focusmanager.FocusedElement to my Textbox.here is the code

<Style x:Key="trgFocus" TargetType="TextBox">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=gvLoginPage, Path=IsVisible}" Value="true">
                    <Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=txtUserName}" />
                </DataTrigger>

            </Style.Triggers>

Now i am getting blinking cursor.Thanks @olitee and @Palak

Related Topic