简体   繁体   English

WPF中的键盘快捷方式路由到ViewModel

[英]Keyboard shortcuts in WPF routed to ViewModel

I wish to receive commands in my ViewModel (ie no code in view at all). 我希望在我的ViewModel中接收命令(即根本没有代码)。 I have setup KeyBindings in the view but I'm unsure how to construct the command on the view model, how do I do this? 我在视图中设置了KeyBindings,但我不确定如何在视图模型上构造命令,我该怎么做? I have tried the code below but it is never called. 我已经尝试了下面的代码,但从未调用过。

I receive this error in the output window 我在输出窗口中收到此错误

BindingExpression path error: 'ShowHelp' property not found on 'object' ''String' (HashCode=-1833871577)'. BindingExpression路径错误:'object'''String'(HashCode = -1833871577)'上找不到'ShowHelp'属性。 BindingExpression:Path=ShowHelp; BindingExpression:路径= ShowHelp; DataItem='String' (HashCode=-1833871577); DataItem ='String'(HashCode = -1833871577); target element is 'KeyBinding' (HashCode=60325168); target元素是'KeyBinding'(HashCode = 60325168); target property is 'Command' (type 'ICommand') target属性是'Command'(类型'ICommand')

viewModel is defined like so: (note this works for all other binding in the window) viewModel的定义如下:(注意这适用于窗口中的所有其他绑定)

<app:ViewModel x:Key="viewModel"></app:ViewModel>

XAML: XAML:

<Window.InputBindings>
    <KeyBinding Command="{Binding ShowHelp, Source=viewModel}" Gesture="ALT+H" />
</Window.InputBindings>

ViewModel Code ViewModel代码

This is where I have started with the ViewModel code to execute the command, if this is wrong please advise :) 这是我开始使用ViewModel代码执行命令的地方,如果这是错误的请指教:)

public class ShowHelpCommand : ICommand
{
    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;

    public void Execute(object parameter)
    {
        Console.WriteLine("SHOW HELP");
    }
}
public ICommand ShowHelp { get;  set; }
ShowHelp = new ShowHelpCommand();

The easiest way is to use the DelegateCommand<T> that is in the Microsoft Prism Library ( http://msdn.microsoft.com/en-us/library/ff653940.aspx ) 最简单的方法是使用Microsoft Prism Library中的DelegateCommand <T>( http://msdn.microsoft.com/en-us/library/ff653940.aspx

Your code would then look something like this: 您的代码看起来像这样:

ShowHelp = new DelegateCommand<object>(param => MethodToExecute)
private void MethodToExecute(object param) {
    //...
}

If you don't want to include the Prism library in your project, it's pretty easy to roll your own delegate command implementation, all you need to do is implement the ICommand interface and pass in and store an Action and Func and execute them in the implementation of Execute and CanExecute. 如果您不想在项目中包含Prism库,那么滚动您自己的委托命令实现非常容易,您需要做的就是实现ICommand接口并传入并存储Action和Func并在执行Execute和CanExecute。

是不是缺少StaticResource?

<KeyBinding Command="{Binding ShowHelp, Source={StaticResource viewModel}}" Gesture="ALT+H" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM