33

Is it possible, to set the autofocus to the textbox in my xaml file?

<Window x:Class="WpfApplication1.Views.Test1"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Height="100"
            Width="210"
            WindowStartupLocation="CenterOwner"
            ShowInTaskbar="False"
            Background="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"
            ResizeMode="CanResizeWithGrip">
    <TextBox HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Visible" TextWrapping="Wrap" AcceptsReturn="True" Text="{Binding Path=Text, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
</Window>
David
  • 4,027
  • 10
  • 50
  • 102

4 Answers4

32
<TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" />
LPL
  • 16,827
  • 6
  • 51
  • 95
  • 4
    I don't know why but this doesn't work for me. However, the other suggestion putting this attached property in header with Binding to ElementName works for me. Without binding, it throws an exception. – newman Feb 05 '13 at 21:54
  • 2
    For some reason doesn't work when `TextBox` is not the only control in the window. – Konstantin Spirin Apr 28 '17 at 06:29
  • 2
    When the TextBox is not the only control in the window/usercontrol use `FocusManager.FocusedElement="{Binding ElementName=MyTextBox}"` in the containing control, e.g. Grid or StackPanel – David Savage Jan 24 '19 at 10:04
16

yes you can use FocusManager.FocusedElement attached property.

FocusManager.FocusedElement="{Binding ElementName=textBox1}"
user1399377
  • 469
  • 2
  • 7
  • 19
10

try somethind like this

<Window x:Class="WpfApplication18.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="500" Width="525" FocusManager.FocusedElement="textcontrol">
    <Grid>
       <TextBox Name="textcontrol" />
    </Grid>
</Window>
Dean Chalk
  • 20,076
  • 6
  • 59
  • 90
10

I think binding is an overkill, Reference is more lightweight:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        FocusManager.FocusedElement="{x:Reference textBox1}">
    <StackPanel>
        <TextBox x:Name="textBox1" />
    </StackPanel>
</Window>
Konstantin Spirin
  • 20,609
  • 15
  • 72
  • 90