Search code examples
.netwpfmvvmkey-bindingswinforms-interop

Winform->WPF MVVM Keybinding Error?


I need some assistance in getting WPF KeyBindings working when being called from a WinForm application. I've created what I think is the basic parts to demonstrate the problem. I can provide an sample application if that helps.

The WinForm application starts a form which has a button that calls the WPF

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim view As New WpfPart.MainWindow
    System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(view)
    view.ShowDialog()
End Sub

With WPF view creates it's view model and sets up the keybings:

<Window x:Class="WpfPart.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:vm="clr-namespace:WpfPart.ViewModels"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <vm:MainWindowViewModel />
</Window.DataContext>
<Window.InputBindings>
    <KeyBinding Key="Escape" Command="{Binding OpenCommand}" Modifiers="Control" />
</Window.InputBindings>
<Grid>

</Grid>

The ViewModel uses a DelagateCommand to hopefully link everything up

using System;
using System.Windows;
using System.Windows.Input;
using WpfPart.Commands;

namespace WpfPart.ViewModels
{
class MainWindowViewModel
{
    private readonly ICommand openCommand;

    public MainWindowViewModel()
    {
        openCommand = new DelegateCommand(Open, CanOpenCommand);
    }

    public ICommand OpenCommand { get { return openCommand; } }
    private bool CanOpenCommand(object state)
    {
        return true;
    }

    private void Open(object state)
    {
        MessageBox.Show("OpenCommand executed.");
    }
}
}

Can anyone see where it is going wrong, the keypress does nothing?!?


Solution

  • To make the KeyBinding work you need to add a CommandReference to your Window.Resources, and then reference the CommandReference from your KeyBinding (not the Command).

    I also used Control-X to avoid opening the Start button in Windows that maps to Control-Escape.

    Here is the XAML you can use based on your question:

    <Window.Resources>
        <!-- Allows a KeyBinding to be associated with a command defined in the View Model  -->
        <c:CommandReference x:Key="OpenCommandReference" Command="{Binding OpenCommand}" />
    </Window.Resources>
    <Window.InputBindings>
        <KeyBinding Key="X" Command="{StaticResource OpenCommandReference}" Modifiers="Control" />
    </Window.InputBindings>