如何将焦点设置在文本框或密码框上

问题描述 投票:2回答:2

当我登录我的应用程序时如何设置焦点,当登录窗口打开时我想在不使用鼠标的情况下输入密码

<PasswordBox x:Name="passwordbox"  Grid.Row="1" Grid.Column="1"  Margin="5,35,5,5" Width="280"  Height="27" app:PasswordBoxAssistant.BindPassword="true" app:PasswordBoxAssistant.BoundPassword="{Binding TechUserModel.UserId,Mode=TwoWay,ValidatesOnDataErrors=True,UpdateSourceTrigger=PropertyChanged}"  HorizontalAlignment="Left" VerticalAlignment="Center"> 
wpf xaml textbox focus passwordbox
2个回答
2
投票

我已经为这种情况尝试了各种解决方案,我发现最有效的是使用FocusManager.FocusedElement:

<Window x:Class="StackOverflow.Test"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Test" Height="300" Width="300"
        FocusManager.FocusedElement="{Binding ElementName=Box}">
    <Grid>
        <TextBox x:Name="Box"/>
    </Grid>
</Window>

0
投票

解:

passwordbox.Focus();

或者在.xaml文件中包含元素中的以下内容作为其属性。

FocusManager.FocusedElement="{Binding ElementName=passwordbox}">

注意:

如果要在表单首次出现时决定将焦点放在哪个控件上,请将代码放在Loaded事件中。

Loaded += (o, e) => {
  passwordbox.Focus();
};
© www.soinside.com 2019 - 2024. All rights reserved.