我正在使用 CAL/Prism 构建一个复合应用程序。主要区域是一个选项卡控件,其中包含多种类型的 View 。每个 View 都有一个可以处理的自定义命令集,这些命令绑定(bind)到窗口顶部的工具栏按钮。我之前在非 CAL 应用程序中通过简单地在命令上设置 InputBinding 来完成此操作,但我无法在 CAL 模块的源代码中找到任何此类机制。
我的问题是,将击键连接到我的 View 的最佳方法是什么,以便当用户按下 Alt + T 时,关联的 DelegateCommand 对象会处理它?连接快捷方式不会那么困难......
最佳答案
仅供引用,CommandReference 类目前不包含在您可以引用的程序集中,但包含在 M-V-VM 项目模板中。因此,如果您不从模板构建应用程序,那么您必须从其他地方获取类。我选择从示例项目中复制它。我将它包含在下面是为了让每个人都可以轻松访问这一小块的好处,但请务必检查 future 版本的 M-V-VM 工具包中模板的更新。
/// <summary>
/// This class facilitates associating a key binding in XAML markup to a command
/// defined in a View Model by exposing a Command dependency property.
/// The class derives from Freezable to work around a limitation in WPF when data-binding from XAML.
/// </summary>
public class CommandReference : Freezable, ICommand
{
public CommandReference( )
{
}
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register( "Command", typeof( ICommand ), typeof( CommandReference ), new PropertyMetadata( new PropertyChangedCallback( OnCommandChanged ) ) );
public ICommand Command
{
get { return (ICommand)GetValue( CommandProperty ); }
set { SetValue( CommandProperty, value ); }
}
#region ICommand Members
public bool CanExecute(object parameter)
{
if (Command != null)
return Command.CanExecute( parameter );
return false;
}
public void Execute(object parameter)
{
Command.Execute( parameter );
}
public event EventHandler CanExecuteChanged;
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CommandReference commandReference = d as CommandReference;
if (commandReference != null)
{
ICommand oldCommand = e.OldValue as ICommand;
if (oldCommand != null)
oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
ICommand newCommand = e.NewValue as ICommand;
if (newCommand != null)
newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
}
}
#endregion
#region Freezable
protected override Freezable CreateInstanceCore( )
{
return new CommandReference();
}
#endregion
}
享受!
关于wpf - 如何在 Composite WPF 中将按键与 DelegateCommand 相关联?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468362/