How to set autofocus only in xaml?

坚强是说给别人听的谎言 提交于 2019-11-29 05:28:13
<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.

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