【问题标题】:How to set autofocus only in xaml?如何仅在 xaml 中设置自动对焦?
【发布时间】:2012-06-28 14:12:05
【问题描述】:

是否可以将自动对焦设置为我的 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>

【问题讨论】:

    标签: wpf xaml textbox autofocus


    【解决方案1】:
    <TextBox FocusManager.FocusedElement="{Binding RelativeSource={RelativeSource Self}}" />
    

    【讨论】:

    • 我不知道为什么,但这对我不起作用。但是,将这个附加属性放在带有绑定到 ElementName 的标题中的另一个建议对我有用。没有绑定,就会抛出异常。
    • TextBox 不是窗口中的唯一控件时,由于某种原因不起作用。
    • 当 TextBox 不是窗口/用户控件中的唯一控件时,在包含控件中使用 FocusManager.FocusedElement="{Binding ElementName=MyTextBox}",例如网格或堆栈面板
    【解决方案2】:

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

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

    【讨论】:

    • 有什么办法可以不加名字吗?
    【解决方案3】:

    试试这样的方法

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

    【讨论】:

    • 有什么办法可以不加名字吗?
    • FocusManager.FocusedElement="{Binding ElementName=textcontrol}"
    【解决方案4】:

    我认为绑定是大材小用,Reference 更轻量级:

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

    【讨论】:

    • this 和 binding 之间真的有性能差异吗?
    • @CodeHxr,我认为要问的正确问题是,当引用确实足够时,使用绑定是否有任何好处。
    最近更新 更多