我只能建议,以改善是通过结合一个static命令实例来移除事件处理程序的需要。
注:这个,因为它需要绑定到KeyBinding
属性的能力只会工作,在.NET 4起。
首先,创建需要一个窗口作为参数,并调用Close
的Execute
方法中的命令:
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
到静态Instance
属性:
<Window.InputBindings>
<KeyBinding Key="Escape" Command="{x:Static local:CloseThisWindowCommand.Instance}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" />
</Window.InputBindings>
我不知道这是必然比你的更好的方法,但它在每一个顶部略微意味着少样板和你没有需要在每个
可这导致内存泄漏,因为单身人士有一个'EventHandler'? – Maslow 2016-04-07 13:56:30
它不应该这样做,因为我们并不关心'CanExecute'功能,您可以通过让'CanExecute'始终返回true并用空附件实现替换'CanExecuteChanged'处理程序(例如'public event EventHandler CanExecuteChanged {add {} remove {}}') – 2016-04-07 14:00:14