如何为“项目中的所有WPF窗口分配”关闭退出键按下“行为? [英] How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

查看:183
本文介绍了如何为“项目中的所有WPF窗口分配”关闭退出键按下“行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有什么简单的方法告诉整个WPF应用程序通过尝试关闭当前关注的寡妇对逃脱键按下作出反应?这不是手动设置命令和输入绑定的麻烦,但我想知道是否在所有窗口重复这个XAML是最优雅的方法?

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>

欢迎任何建设性建议!

推荐答案

我可以建议改进的是通过绑定到一个静态命令实例来删除对事件处理程序的需要。

All I can suggest to improve on that is to remove the need for an event handler by binding to a static command instance.

注意:这只能在.NET 4以上,因为它需要绑定到 KeyBinding 属性。

Note: this will only work in .NET 4 onwards as it requires the ability to bind to the KeyBinding properties.

首先,创建一个以Window作为参数并在 Execute 方法中调用关闭的命令:

First, create a command that takes a Window as a parameter and calls Close within the Execute method:

public class CloseThisWindowCommand : ICommand
{
    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        //we can only close Windows
        return (parameter is Window);
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        if (this.CanExecute(parameter))
        {
            ((Window)parameter).Close();
        }
    }

    #endregion

    private CloseThisWindowCommand()
    {

    }

    public static readonly ICommand Instance = new CloseThisWindowCommand();
}

然后你可以绑定 KeyBinding 到静态实例属性:

Then you can bind your KeyBinding to the static Instance property:

<Window.InputBindings>
    <KeyBinding Key="Escape" Command="{x:Static local:CloseThisWindowCommand.Instance}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" />
</Window.InputBindings>

我不知道这必然比你的方法更好但它确实意味着在每个 Window 的顶部略微少了样板,并且您不需要在每个

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 each

这篇关于如何为“项目中的所有WPF窗口分配”关闭退出键按下“行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆