iView
iView

Reputation: 21

WPF - set focus on textbox

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.

Upvotes: 1

Views: 3706

Answers (1)

Tomtom
Tomtom

Reputation: 9394

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

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

Upvotes: 2

Related Questions