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