Is there any straightforward way of telling the whole WPF application to react to Escape key presses by attempting to close the currently focused widow? It is not a great bother to manually setup the command- and input bindings but I wonder if repeating this XAML in all windows is the most elegant approach?
<Window.CommandBindings>
<CommandBinding Command="Close" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="Escape" Command="Close" />
</Window.InputBindings>
Any constructive suggestions welcome!
Or you could just add a button with Cancel as text and set
IsCancel = True
. Then Escape will work as default command to close.All I can suggest to improve on that is to remove the need for an event handler by binding to a static command instance.
Note: this will only work in .NET 4 onwards as it requires the ability to bind to the
KeyBinding
properties.First, create a command that takes a Window as a parameter and calls
Close
within theExecute
method:Then you can bind your
KeyBinding
to the staticInstance
property:I don't know that this is necessarily better than your approach, but it does mean marginally less boilerplate at the top of every
Window
and that you don't need to include an event handler in eachAnother possible way is to use attached properties
Bellow is a gist code:
create
RoutedUICommand
like belowand add it command binding in constructor
On
Window
s shown withShowDialog()
you can use:None of above worked for me, except Kai's. I modified his answer: I added 'btn_close.IsCancel = true;' to constructor. SettingsWindow is my second window, and main window is (default) MainWindow.
Hope it helps,
Simon S love nia