如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:19:39  来源:igfitidea点击:

How to make a submit button in WPF?

wpfsubmitkeypress

提问by Jader Dias

When you press Enteranywhere in a HTML formit triggers its action, that is equivalent of pressing the submitbutton. How to make a window that when I press Enteranywhere it will trigger an event?

当您按下EnterHTML 中的任意位置时,form它会触发它的action,这相当于按下submit按钮。如何制作一个窗口,当我按下 Enter任何地方时它会触发一个事件?

回答by Alex B

Set the IsDefaultproperty on the buttonto true to enable the Enterkey to activate that button's action. There is also the IsCancelproperty that does the same thing for the Escapekey.

按钮上IsDefault属性设置为 true 以启用该键以激活该按钮的操作。还有一个属性对密钥做同样的事情。EnterIsCancelEscape

回答by ihatemash

Assign the PreviewKeyDownevent to the window in XAML then check the KeyEventArgsin 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 DatePickercontrol will swallow the Enterkeypress so the default button doesn't get clicked. I wrote this event handler to fix that. Use the PreviewKeyUpto ensure that the DatePickerperforms 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);
    }
}