How to set autofocus only in xaml?

心已入冬 提交于 2019-11-27 22:59:42

问题


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>

回答1:


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



回答2:


yes you can use FocusManager.FocusedElement attached property.

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



回答3:


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>



回答4:


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>



回答5:


I usually resolve this with C#

textBox1.Focus();

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



来源:https://stackoverflow.com/questions/11246554/how-to-set-autofocus-only-in-xaml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!