31

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>
4

5 回答 5

30
<TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" />
于 2012-06-28T16:16:45.557 回答
16

yes you can use FocusManager.FocusedElement attached property.

FocusManager.FocusedElement="{Binding ElementName=textBox1}"
于 2012-06-28T14:16:44.867 回答
9

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>
于 2012-06-28T14:17:06.360 回答
8

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>
于 2017-04-28T06:33:03.737 回答
-9

I usually resolve this with C#

textBox1.Focus();

I think it is the best way how to do this.

于 2013-02-05T22:53:19.843 回答