4

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.

Community
  • 1
  • 1
shreesha
  • 1,811
  • 2
  • 21
  • 30
  • http://stackoverflow.com/questions/19225443/set-focus-on-a-textbox-control-in-usercontrol-in-wpf – Palak.Maheria Jul 20 '15 at 12:44
  • I have already checked this link.but i want to know is there a way to do it using only xaml.otherwise i can use Keyboard.Focus method also. – shreesha Jul 20 '15 at 13:26
  • Using only xaml to set focus is already mentioned in the same link. Please check all the answers. – Palak.Maheria Jul 20 '15 at 13:29
  • The link above shows a method of achieving this without breaking the MVVM pattern. If you want a pure XAML approach, you could adapt that example to use an event trigger that fires on the window `Loaded` event. – olitee Jul 20 '15 at 13:30

1 Answers1

6

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

shreesha
  • 1,811
  • 2
  • 21
  • 30