How can I assign the 'Close on Escape-key pres

2019-02-01 21:14发布

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!

7条回答
Root(大扎)
2楼-- · 2019-02-01 22:04

You can also use PreviewKeyDown Event

PreviewKeyDown="UserControl_PreviewKeyDown"

Code behind call you close command

private void UserControl_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Escape)
            {
                _vm.OnCloseCommand(sender);
            }
        }
查看更多
登录 后发表回答