5

我有一个基本的登录页面,

    <TextBox x:Name="UsernameInput" HorizontalAlignment="Left" TextWrapping="Wrap" Text="{Binding Username, Mode=TwoWay}" VerticalAlignment="Center" Grid.Row="0" Grid.Column="2" Width="400" />
    <PasswordBox HorizontalAlignment="Left" VerticalAlignment="Center" Password="{Binding Password, Mode=TwoWay}" Grid.Row="1" Grid.Column="2" Width="400"/>
    <TextBlock HorizontalAlignment="Right" TextWrapping="Wrap" Text="Username: " VerticalAlignment="Center" Margin="0,0,0,15" Grid.Row="0" Grid.Column="0" Style="{StaticResource SubheaderTextStyle}"/>
    <TextBlock HorizontalAlignment="Right" TextWrapping="Wrap" Text="Password: " VerticalAlignment="Center" Margin="0,0,0,15" Grid.Row="1" Grid.Column="0" Style="{StaticResource SubheaderTextStyle}"/>

    <Button Content="Login" HorizontalAlignment="Center" VerticalAlignment="Center" Grid.Row="2" Grid.Column="2" Height="50" Width="300" Command="{Binding LoginCommand}"/>

如果用户从密码字段中按 Enter 键,我如何模拟按下的“登录”按钮?

谢谢!

4

3 回答 3

14

You can use KeyDown event of PasswordBox.

<PasswordBox KeyDown="txtPassword_KeyDown"/>

private void txtPassword_KeyDown(object sender, KeyRoutedEventArgs e)
{
    if (e.Key == Windows.System.VirtualKey.Enter)
        //TODO: do login
}
于 2013-07-03T15:53:42.807 回答
1

在 PasswordBox 中使用KeyDown事件 -

<PasswordBox KeyDown="PasswordKeyDown"/>

然后在您的 c# 代码中检查是否已按下回车键,并相应地登录:

using System.Windows.Input;

private void PasswordKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
        Login();
}
于 2013-07-03T15:10:46.253 回答
1

如果您希望所有输入字段在按下 Enter 时启动“登录”按钮,您可以使用 ButtonIsDefault属性并将其设置为 True,您可以在此处阅读更多信息。

当设置为 true 时,如果在窗口中的某些对象有焦点时按回车,按钮的单击事件代码将自动触发。

如果您只想PasswordBox启动“登录”按钮,您可以keyDown在 xaml 中添加属性:

<PasswordBox KeyDown="Password_KeyDown"/>

并在 C# 中添加:

private void Password_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
        Login();
}
于 2020-07-28T21:38:03.660 回答