Keyboard shortcuts in WPF routed to ViewModel

I wish to receive commands in my ViewModel (i.e. no code in view at all). 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? 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:Path=ShowHelp; DataItem='String' (HashCode=-1833871577); target element is 'KeyBinding' (HashCode=60325168); target property is 'Command' (type 'ICommand')

viewModel is defined like so: (note this works for all other binding in the window)

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

XAML:

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

ViewModel Code

This is where I have started with the ViewModel code to execute the command, if this is wrong please advise :)

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();

Answers


Isn't it a missing StaticResource?

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

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)

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.


Need Your Help

Catch ErrorException that wraps a fatal PHP error

php error-handling fatal-error

In my homemade PHP MVC framework, I've written a little error handler that wraps PHP errors in an exception, then throws it.

How to keep a circle inside another circle android view control

android view control circle pad

I am trying to create a pad-like view in android. I got a circle that follows user's gestures and I am using distance to keep the circle of going outside the main circle of the pad control.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.