在密码框中捕获返回键的最佳方法是什么? (WPF/XAML)

发布于 2024-07-27 18:39:00 字数 237 浏览 3 评论 0原文

在密码框中捕获返回键的最佳方法是什么? (WPF/XAML)

我的登录表单上有一个文本框字段和一个密码框字段(用于输入用户名和密码)。 我还有一个登录按钮,它调用执行登录验证过程的方法。

我需要使 Return 键在 PasswordBox 中以相同的方式做出反应,以便用户可以选择输入用户名和密码,然后只需按 Return 即可登录。

有谁知道在 WPF 中这是如何完成的? 任何帮助表示赞赏。

What's the best way to catch the return key in a PasswordBox? (WPF/XAML)

I have a TextBox field and a PasswordBox field on my login form (for username and password entry). I also have a login button which invokes the method that performs the login validation process.

I need to make the Return key react the same way in the PasswordBox, so that the user can have the option enter their username and password and simply hit Return to log in.

Does anyone know how this is done in WPF? Any help is appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

开始看清了 2024-08-03 18:39:00

有一种更简单的机制来激活按钮的代码。 WPF Button 类提供了一个名为 IsDefault 的属性。 当设置为 true 时,如果在窗口中的某些对象具有焦点时按回车键,则会自动触发按钮的单击事件的代码。 这种机制就像密码盒的魅力一样。

There is an even easier mechanism to activate the button's code. WPF Button class provides a property called IsDefault. When set to true, if you press return while some objects in the window have focus, the code of the click event of the button will be fired automatically. This mechanism works like a charm with the passwordbox.

哆兒滾 2024-08-03 18:39:00

您可以处理PasswordBox(和TextBox,如果需要)上的KeyDown 事件,然后使用以下事件处理程序——

private void OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Return && e.Key != Key.Enter)
        return;
    e.Handled = true;
    HandleEnter();
}

You can handle the KeyDown event on the PasswordBox (and TextBox if desired) and then use the following event handler --

private void OnKeyDown(object sender, KeyEventArgs e)
{
    if (e.Key != Key.Return && e.Key != Key.Enter)
        return;
    e.Handled = true;
    HandleEnter();
}
左耳近心 2024-08-03 18:39:00

您可以尝试使用 RoutedCommand。

您可以在按钮的 Command 属性上设置它。
您还可以将 KeyGesture 添加到登录表单的 InputBindings 中,以绑定 Enter 键来触发 RoutedCommand。

然后在登录表单的 CommandBindings 中添加 CommandBinding,将 RoutedCommand 绑定到代码中的执行处理程序,并执行或触发登录验证过程。

You could try using a RoutedCommand.

You can set it on the Command property of the Button.
You can also add a KeyGesture to the InputBindings of your loginform to bind the Enter key to trigger your RoutedCommand.

Then add a CommandBinding in the CommandBindings of your loginform to bind the RoutedCommand to Executed handlers in your code and perform or trigger your login validation process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文