Jonathan Birkholz

How to Bind Custom ICommands to Input Bindings

If you are developing using any sort of V-VM-M pattern, you are already loving the awesome binding powers of Wpf.

And you should also be loving ICommand and binding buttons to ICommand properties on your VM.

What you might have discovered is that binding ICommands to Keys and other input gestures is not as easy as it was with vanilla Routed Commands.

But have no fear! There is a solution.

By utilizing Josh Smith’s Element Spy trick and creating a custom InputBinding, we can gain the functionality of binding an ICommand to a Key, etc.

Here is my custom input binding :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class MyInputBinding : KeyBinding
{
#region Fields
private static readonly DependencyProperty BoundCommandProperty =
DependencyProperty.Register("BoundCommand",
typeof (ICommand),
typeof (MyInputBinding),
new PropertyMetadata(OnBoundCommandChanged));
#endregion
#region Properties
public ICommand BoundCommand
{
get { return GetValue(BoundCommandProperty) as ICommand; }
set { SetValue(BoundCommandProperty, value);}
}
#endregion
#region Methods
private static void OnBoundCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
MyInputBinding binding = obj as MyInputBinding;
if (binding == null) return;
binding.Command = e.NewValue as ICommand;
}
#endregion
}

Then when you combine the use of the ElementSpy, your xaml looks like:

1
2
3
4
5
6
7
8
<Window.Resources>
<InputBindingSandbox:ElementSpy x:Key="spy" />
</Window.Resources>
<Window.InputBindings>
<InputBindingSandbox:MyInputBinding BoundCommand="{Binding Source={StaticResource spy},
Path=Element.DataContext.MyCommand}"
Key="Enter" />
</Window.InputBindings>

Naturally the custom input binding is very simple and does not expose the Command Parameter nor the Command Target, etc. But the basic pattern is there so feel free to utilize and extend.

Happy coding!

C#, WPF