是否有任何直接的方式告诉整个 WPF 应用程序通过尝试关闭当前获得焦点的窗口来对 Escape 键按下作出 react ?手动设置命令和输入绑定(bind)并不是一件大事,但我想知道在所有窗口中重复此 XAML 是否是最优雅的方法?
<Window.CommandBindings>
<CommandBinding Command="Close" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<Window.InputBindings>
<KeyBinding Key="Escape" Command="Close" />
</Window.InputBindings>
欢迎任何建设性的建议!
最佳答案
我所能提出的改进建议是通过绑定(bind)到静态命令实例来消除对事件处理程序的需求。
注意:这仅适用于 .NET 4 及更高版本,因为它需要能够绑定(bind)到 KeyBinding
属性。
首先,创建一个以 Window 作为参数并在 Execute
方法中调用 Close
的命令:
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
绑定(bind)到静态Instance
属性:
<Window.InputBindings>
<KeyBinding Key="Escape" Command="{x:Static local:CloseThisWindowCommand.Instance}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" />
</Window.InputBindings>
我不知道这一定比您的方法更好,但它确实意味着每个 Window
顶部的样板文件略少,而您没有需要在每个中包含一个事件处理程序
关于wpf - 如何将 'Close on Escape-key press' 行为分配给项目中的所有 WPF 窗口?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3863431/