それを改善するために提案できるのは、静的コマンドインスタンスにバインドすることでイベントハンドラーの必要性をなくすことだけです。
注:これは、プロパティにバインドする機能が必要なため、.NET4以降でのみ機能しKeyBinding
ます。
まず、ウィンドウをパラメーターとして受け取り、メソッド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>
これが必ずしもあなたのアプローチよりも優れているかどうかはわかりませんが、すべての上部の定型文がわずかに少なくなりWindow
、それぞれにイベントハンドラーを含める必要がないことを意味します