我正在使用 CAL/Prism 构建一个复合应用程序。主要区域是一个选项卡控件,其中包含多种类型的视图。每个视图都有一个可以处理的自定义命令集,这些命令绑定到窗口顶部的工具栏按钮。我之前在非 CAL 应用程序中通过简单地在命令上设置 InputBinding 来完成此操作,但我无法在 CAL 模块的源代码中找到任何此类机制。
我的问题是,将击键连接到我的视图的最佳方法是什么,以便当用户按下Alt+T时,相关的 DelegateCommand 对象会处理它?连接快捷方式不会那么困难......
我正在使用 CAL/Prism 构建一个复合应用程序。主要区域是一个选项卡控件,其中包含多种类型的视图。每个视图都有一个可以处理的自定义命令集,这些命令绑定到窗口顶部的工具栏按钮。我之前在非 CAL 应用程序中通过简单地在命令上设置 InputBinding 来完成此操作,但我无法在 CAL 模块的源代码中找到任何此类机制。
我的问题是,将击键连接到我的视图的最佳方法是什么,以便当用户按下Alt+T时,相关的 DelegateCommand 对象会处理它?连接快捷方式不会那么困难......
仅供参考,CommandReference类目前不包含在您可以引用的程序集中,但包含在 MV-VM 项目模板中。因此,如果您不从模板构建应用程序,那么您必须从其他地方获取类。我选择从示例项目中复制它。我将它包含在下面是为了让每个人都可以轻松访问这一小块的好处,但请务必在 MV-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
}
享受!
MVVM Toolkit有一个名为 a 的类,CommandReference
它允许您使用对命令的引用作为键绑定。
<Window ...
xmlns:toolkit="clr-namespace:CannotRememberNamspace;assembly=OrTheAssembly"
>
<Window.Resources>
<toolkit:CommandReference
x:Key="ExitCommandReference"
Command="{Binding ExitCommand}" />
</Window.Resources>
<Window.InputBindings>
<KeyBinding Key="X"
Modifiers="Control"
Command="{StaticResource ExitCommandReference}" />
</Window.InputBindings>
</Window>
这样就可以了。
编辑:由于这是编写的,WPF 4.0 修复了这个特定问题,您不再需要使用静态资源解决方法。您可以直接从 KeyBinding 引用视图模型中的命令。
查看这些文章:http ://coderscouch.com/tags/input%20bindings 。他们应该是有帮助的。