如何仅在xaml中设置自动对焦?

Dav*_*vid 26 wpf xaml textbox autofocus

是否可以将自动对焦设置为我的xaml文件中的文本框?

<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>
Run Code Online (Sandbox Code Playgroud)

LPL*_*LPL 24

<TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" />
Run Code Online (Sandbox Code Playgroud)

  • 我不知道为什么,但这对我不起作用.但是,另一个建议将此附加属性放在带有Binding到ElementName的标题中对我有用.没有绑定,它会抛出异常. (3认同)
  • 由于某种原因,当“TextBox”不是窗口中唯一的控件时,该控件不起作用。 (2认同)
  • 当 TextBox 不是窗口/用户控件中的唯一控件时,请在包含控件(例如 Grid 或 StackPanel)中使用 `FocusManager.FocusedElement="{Binding ElementName=MyTextBox}"` (2认同)

use*_*377 15

是的,您可以使用FocusManager.FocusedElement附加属性.

FocusManager.FocusedElement="{Binding ElementName=textBox1}"
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法,这个没有名字? (3认同)

Dea*_*alk 8

尝试这样的事情

<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>
Run Code Online (Sandbox Code Playgroud)

  • 有没有办法,这个没有名字? (4认同)

Kon*_*rin 6

我认为绑定是一种矫枉过正,参考更轻量级:

<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>
Run Code Online (Sandbox Code Playgroud)