如何在 WPF 中制作提交按钮?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4194470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make a submit button in WPF?
提问by Jader Dias
When you press Enteranywhere in a HTML form
it triggers its action
, that is equivalent of pressing the submit
button.
How to make a window that when I press Enteranywhere it will trigger an event?
当您按下EnterHTML 中的任意位置时,form
它会触发它的action
,这相当于按下submit
按钮。如何制作一个窗口,当我按下 Enter任何地方时它会触发一个事件?
回答by Alex B
回答by ihatemash
Assign the PreviewKeyDown
event to the window in XAML then check the KeyEventArgs
in codebehind to determine if the user pressed the Enterkey.
将PreviewKeyDown
事件分配给 XAML 中的窗口,然后检查代码KeyEventArgs
隐藏以确定用户是否按下了Enter键。
XAML code:
XAML 代码:
<Window
[...]
PreviewKeyDown="Window_PreviewKeyDown">
Code behind:
后面的代码:
private void Window_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
// Whatever code you want if enter key is pressed goes here
}
}
回答by Walter Stabosz
I found that the DatePicker
control will swallow the Enterkeypress so the default button doesn't get clicked. I wrote this event handler to fix that. Use the PreviewKeyUp
to ensure that the DatePicker
performs its date formatting code before clicking the default button.
我发现DatePicker
控件会吞下Enter按键,因此不会点击默认按钮。我写了这个事件处理程序来解决这个问题。使用PreviewKeyUp
确保DatePicker
在单击默认按钮之前执行其日期格式化代码。
private void DatePicker_PreviewKeyUp(object sender, KeyEventArgs e) {
// event handler to click the default button when you hit enter on DatePicker
if (e.Key == Key.Enter) {
// https://www.codeproject.com/Tips/739358/WPF-Programmatically-click-the-default-button
System.Windows.Input.AccessKeyManager.ProcessKey(null, "\x000D", false);
}
}