Set the focus on a textbox in xaml wpf Set the focus on a textbox in xaml wpf wpf wpf

Set the focus on a textbox in xaml wpf


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.


You can apply this property directly on the TextBox :

<TextBox Text="{Binding MyText}" FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}"/>


I am new to using WPF and reading through the above examples I had a similar experience trying set the focus to a textbox using the xaml code examples given, i.e. all the examples above didn't work.

What I found was I had to place the FocusManager.FocusElement in the page element. I assume this would probably work as well if you used a Window as the parent element. Anyway, here is the code that worked for me.

 <Page x:Class="NameOfYourClass"  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"   xmlns:d="http://schemas.microsoft.com/expression/blend/2008"   mc:Ignorable="d"  Title="Title"   Height="720"  Width="915"  Background="white"  Loaded="pgLoaded"  FocusManager.FocusedElement="{Binding ElementName=NameOfYourTextBox}">  <!-- Create child elements here. -->  </Page>