0
votes

In my WPF application I have many text boxes on one page. I want to set focus on the first text box. I've Googled it and tried different solutions.

XAML Code :

<StackPanel Width="350" HorizontalAlignment="Left" >
    <TextBlock x:Name="CustNamelbl" Text="C U S T O M E R  N A M E"
               Style="{StaticResource LightBoldTxtblkStyle }"/>
    <Grid Height="35">
         <TextBox x:Name="CustName" Style="{StaticResource Txtbox}"
                  LostFocus="CustName_LostFocus_1"   TabIndex="1"
                  CommandManager.PreviewExecuted="CustName_PreviewExecuted"
                  ContextMenu="{x:Null}" PreviewTextInput="CustName_PreviewTextInput"
                  Margin="0,0,0,0" GotFocus="CustName_GotFocus"/>
         <Rectangle Fill="White" Height="2" Opacity="0.2" 
                    VerticalAlignment="Bottom"></Rectangle>
   </Grid>
</StackPanel>   

C# Code :

CustName.Focus();
Keyboard.Focus(CustName);

Using this code I am getting Focus on that TextBox. I'm also able to open system keyboard. However, I am not able to type anything in that TextBox. Also, that focused cursor is not a blinking cursor, but just a steady cursor.

1
Try set focus on loaded event handler. My guess is that you setting focus in constructor. For more details read this: WPF Input Focus OverviewRenatas M.
I think the issue lies within CustName_GotFocus. Try deleting that method from xaml for now and see if that helps.XAMlMAX

1 Answers

2
votes

Give your TextBox a name and then you can call in your Window-Tag

FocusManager.FocusedElement="{Binding ElementName=YOURTBNAME}"