Set the focus on a textbox in xaml wpf

user9969 picture user9969 · May 20, 2010 · Viewed 88.2k times · Source

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?

Answer

Julien Lebosquain picture Julien Lebosquain · May 20, 2010

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.