Click here to Skip to main content
13,557,543 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


5 bookmarked
Posted 20 Mar 2011
Licenced CPOL

InputBinding for WPF and Silverlight with MVVM

, 20 Mar 2011
Rate this:
Please Sign up or sign in to vote.
WPF inputbindings to bind your key and mouse events directly with your ViewModels
With the introduction of MVVM pattern and WPF code structure, we have gradually mould ourselves to separate our presentation layer more with the actual Views. In doing so, we have implemented a lots of interfaces, some corresponds to the Command interfaces using ICommand interface which lets you define your object to handle an Button Click event handlers while some are mere property exposure to handle other textual inputs using INotifyPropertyChanged. I have already talked about them a lot during my past few series of posts. But this is not basically the whole gamut of coding needs that could replace our previous event based approach. Say for instance you want to handle Mouse Gestures, or Key events, what do you do ?
Lets take an example :

Yes for such occasion, you need InputBindings. InputBindings allows you to execute an ICommand interface whenever certain gesture event occurs on the application which is configured to it. Let us look into the code to see how you can use InputBindings in your MVVM applications :

<Window x:Class="InputBindings.MainWindow"




        Title="MainWindow" Height="350" Width="525">
        <local:SampleModel />
        <KeyBinding Command="{Binding BindKeyCommand}"

                    CommandParameter="{Binding ElementName=txtMessage, Path=Text}"


    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock Text="Write your Message" />
        <TextBox x:Name="txtMessage" MinWidth="200"/>


Here in the XAML you would indentify out code creates an object of ViewModel SampleViewModel. The ViewModel is later used from the KeyBinding to allow execution of ICommand interface BindKeyCommand.
Just for your information, the CommandParameter is also used in this situation which sends the Text written on the TextBox txtMessage directly inside the Command interface. Hence we need to tool our ICommand so that it gets the parameter into its interface. Take a look how I built our Command interface.

public class SimpleDelegateCommand : ICommand
Action<object> _executeDelegate;
public SimpleDelegateCommand(Action<object> executeDelegate)
_executeDelegate = executeDelegate;
public void Execute(object parameter)
public bool CanExecute(object parameter) { return true; }
public event EventHandler CanExecuteChanged;

Here the Command interface SimpleDelegateCommand takes the argument parameter from CommandParameter and executes it.
The Key in KeyBinding indicates the Keyboard key event which would have invoked the interface. We specified B explicitely which indicates the Command will execute when the Keyboard B key is pressed. Even Modifier indicates special Keys. Control means ctrl key from the KeyBoard, hence you can say the command will execute only when ctrl + B is pressed on the keyboard.
Now ViewModel looks quite simple as well :

public class SampleModel : INotifyPropertyChanged

private ICommand _BindKeyCommand;
public ICommand BindKeyCommand
this._BindKeyCommand = this._BindKeyCommand ?? new SimpleDelegateCommand(x => MessageBox.Show(string.Format("Command invoked : {0}", x)));
return this._BindKeyCommand;


#region INotifyPropertyChanged Members
public virtual void OnPropertyChanged(string propName)
if (this.PropertyChanged != null)
var pargs = new PropertyChangedEventArgs(propName);
this.PropertyChanged(this, pargs);
public event PropertyChangedEventHandler PropertyChanged;


In the ViewModel we create an object of SimpleDelegateCommand and pass an Action<object>

For your information: You can also use InputBindings for MouseEvents on any control as it inherits directly from UIElement.

Downlod Sample - 71KB[^]

There are still lots of things left to speak on the topic. I will discuss them in a separate tips.
Thanks for reading. I hope this will help you.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Abhishek Sur
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : to know more about Abhishek.

Abhishek also authored a book on .NET 4.5 Features and recommends you to read it, you will learn a lot from it.

Basically he is from India, who loves to explore the .NET world. He loves to code and in his leisure you always find him talking about technical stuffs.

Working as a VP product of APPSeCONNECT, an integration platform of future, he does all sort of innovation around the product.

Have any problem? Write to him in his Forum.

You can also mail him directly to

Want a Coder like him for your project?
Drop him a mail to

Visit His Blog

Dotnet Tricks and Tips

Dont forget to vote or share your comments about his Writing

You may also be interested in...

Comments and Discussions

GeneralThanks Abhishek it helps me.+5 Pin
Algorithm_Seeker29-Jul-11 23:54
memberAlgorithm_Seeker29-Jul-11 23:54 
GeneralReason for my vote of 2 Your title is misleading. Silverligh... Pin
GraGra_3320-Mar-11 12:49
memberGraGra_3320-Mar-11 12:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01-2016 | 2.8.180515.1 | Last Updated 20 Mar 2011
Article Copyright 2011 by Abhishek Sur
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid