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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With