0
votes

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

2 Answers

1
votes

Isn't it a missing StaticResource?

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

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.