How to make a submit button in WPF?
43,017
Solution 1
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
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
}
}
Author by
Jader Dias
Perl, Javascript, C#, Go, Matlab and Python Developer
Updated on March 23, 2021Comments
-
Jader Dias over 3 years
When you press Enter anywhere in a HTML
form
it triggers itsaction
, that is equivalent of pressing thesubmit
button. How to make a window that when I press Enter anywhere it will trigger an event? -
ihatemash over 13 yearsSorry, I just realized you didn't say you have a button on the form. You must have a button on the form before this will work.
-
Guy over 13 yearsIf not, just add IsHitTestVisible="true" to the Window properties
-
ihatemash over 13 yearsThat was my first suggestion in my answer below but then i noticed XMLforDummies didn't say he/she had an "OK" or "Submit" button on the form so i edited my answer. The only "problem" you may run into with this solution is, if a button other than the "OK"/"Submit" button has focus, pressing the enter key will only click the focused button and will not trigger the other event which is probably what you expect but just wanted to bring that point up.
-
Alex B over 13 yearsI think that behavior is intentional. For example, if that button opened a modal dialog, and by hitting the enter key it trigger the submit, you wouldn't want both events to fire.
-
Walter Stabosz over 6 yearsWarning: This event will trigger on any control in the Window, even other buttons. Which is not normally an issue unless your users Tab around the form and use Enter to click buttons.
-
oo_dev over 3 years@WalterStabosz when you tab around, you should use anyway the space button to activate the highlighted button :)