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

时间:2017-04-28 09:14:17

标签: c# wpf

为什么我无法将注意力集中在我的PasswordBox控件上?

C#:

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

XAML:

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

3 个答案:

答案 0 :(得分:5)

当你在构造函数中设置它时,你做得太早了。请尝试使用Load事件处理程序。

public Login()
{
    InitializeComponent();

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

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

您也可以在XAML中执行此操作:

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

答案 1 :(得分:3)

WPF提供了一种非常优雅的方式(仅限xaml)

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

示例:

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

enter image description here

答案 2 :(得分:1)

如果您想在XAML中执行此操作:

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

请注意(MSDN):

  

整个桌面上只有一个元素有键盘   焦点。在WPF中,具有键盘焦点的元素将具有   IsKeyboardFocused设置为true。