Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the focus on a textbox in xaml wpf

Tags:

focus

wpf

textbox

Despite some posts on this forum and others i cannot find something that tells me how to set the focus on a TextBox.

I have a userControl with many labels and textBoxes. When the form is loaded I want the a particular textBox to have the focus.

I have set the tabIndex but that didn't seem to work.

Any suggestions?

like image 875
user9969 Avatar asked May 20 '10 08:05

user9969


People also ask

How do I focus a TextBox in XAML?

You can use the FocusManager. FocusedElement attached property for this purpose. Here's a piece of code that set the focus to TxtB by default. You can also use TxtB.

How do you focus a control in WPF?

When setting initial focus at application startup, the element to receive focus must be in the visual tree of the initial window loaded by the application, and the element must have Focusable and IsVisible set to true . The recommended place to set initial focus is in the Loaded event handler.

What is TextBox focus?

Description: The Focused event fires when the TextBox gains focus - typically when a client clicks/taps on a TextBox to begin text entry. This also fires if a TextBox forces focus on the user. It can be used alongside TextBox.

Which of the following method of TextBox can set focus in TextBox control?

Use the SetFocus method when you want a particular field or control to have the focus so that all user input is directed to this object.


1 Answers

You can use the FocusManager.FocusedElement attached property for this purpose. Here's a piece of code that set the focus to TxtB by default.

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

You can also use TxtB.Focus() in your code-behind if you don't want to do this in XAML.

like image 117
Julien Lebosquain Avatar answered Sep 21 '22 13:09

Julien Lebosquain