我只能建議,以改善是通過結合一個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