How to make a submit button in WPF?

WpfSubmitKeypress

Wpf Problem Overview


When you press Enter anywhere 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 Enter anywhere it will trigger an event?

Wpf Solutions


Solution 1 - Wpf

Set the IsDefault property on the button to true to enable the Enter key to activate that button's action. There is also the IsCancel property that does the same thing for the Escape key.

Solution 2 - Wpf

Assign the PreviewKeyDown event to the window in XAML then check the KeyEventArgs in codebehind to determine if the user pressed the Enter key.

XAML code:

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

Solution 3 - Wpf

I found that the DatePicker control will swallow the Enter keypress 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.

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);
    }
}

Solution 4 - Wpf

<Button Name="btnDefault" IsDefault="true" Click="OnClickDefault">OK</Button>

You can do this by setting the button IsDefault property to True.

You can get detailed information from Microsoft's documents.

Button.IsDefault Property

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJader DiasView Question on Stackoverflow
Solution 1 - WpfAlex BView Answer on Stackoverflow
Solution 2 - WpfihatemashView Answer on Stackoverflow
Solution 3 - WpfWalter StaboszView Answer on Stackoverflow
Solution 4 - WpfhasanadiguzelView Answer on Stackoverflow