質問

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>
役に立ちましたか?

解決

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

他のヒント

yes you can use FocusManager.FocusedElement attached property.

FocusManager.FocusedElement="{Binding ElementName=textBox1}"

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>

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>

I usually resolve this with C#

textBox1.Focus();

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top