简体   繁体   English

应用程序启动时将焦点放在PasswordBox上

[英]Set focus on PasswordBox when application starts

Is there a reason why I can't set the focus on my PasswordBox Control? 我为什么不能将重点放在我的PasswordBox控件上?

C#: C#:

public Login()
{
   InitializeComponent();
   _password.Focus();
}

XAML: XAML:

<PasswordBox x:Name="_password" Width="200" Height="30" FontSize="14" 
 KeyDown="_password_KeyDown"/>

You're doing it too early when you're setting it in the constructor. 在构造函数中进行设置时,还为时过早。 Try the Load event handler instead. 请尝试使用Load事件处理程序。

public Login()
{
    InitializeComponent();

    this.Loaded += new RoutedEventHandler(Login_Loaded);
}

void Login_Loaded(object sender, RoutedEventArgs e)
{
    _password.Focus();
}

You can also do it in XAML: 您也可以在XAML中执行此操作:

  <Window ....
        FocusManager.FocusedElement="{Binding ElementName=_password}"
         ... />

WPF offers a nice elegant way (xaml only) WPF提供了一种很好的优雅方式(仅xaml)

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

Example: 例:

<Window x:Class="WpfApp1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApp1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525"
        FocusManager.FocusedElement="{Binding ElementName=pass}">
    <Grid>
        <Button Content="Button" HorizontalAlignment="Left" Margin="261,165,0,0" VerticalAlignment="Top" Width="75"/>
        <TextBox x:Name="name" HorizontalAlignment="Left" Height="23" Margin="70,193,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>
        <TextBox x:Name="pass" HorizontalAlignment="Left" Height="23" Margin="70,165,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120"/>

    </Grid>
</Window>

在此处输入图片说明

If you want to do it in XAML : 如果要在XAML执行此操作:

<StackPanel FocusManager.FocusedElement="{Binding ElementName=_password}">
   <PasswordBox Name="_password" />
</StackPanel>

Please note ( MSDN ): 请注意( MSDN ):

There can be only one element on the whole desktop that has keyboard focus. 整个桌面上只能有一个具有键盘焦点的元素。 In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true. 在WPF中,具有键盘焦点的元素将IsKeyboardFocused设置为true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM