Click here to Skip to main content
15,887,427 members
Articles / Desktop Programming / WPF
Tip/Trick

InputBinding for WPF and Silverlight with MVVM

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
20 Mar 2011CPOL2 min read 41.3K   5   2
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 :

XML
<Window x:Class="InputBindings.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:InputBindings"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:SampleModel />
    </Window.DataContext>
    <Window.InputBindings>
        <KeyBinding Command="{Binding BindKeyCommand}"
                    CommandParameter="{Binding ElementName=txtMessage, Path=Text}"
                    Key="B"
                    Modifiers="Control"/>
    </Window.InputBindings>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <TextBlock Text="Write your Message" />
        <TextBox x:Name="txtMessage" MinWidth="200"/>
        <Button
            />
    </StackPanel>
</Window>



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.

C#
public class SimpleDelegateCommand : ICommand
{
Action<object> _executeDelegate;
public SimpleDelegateCommand(Action<object> executeDelegate)
{
_executeDelegate = executeDelegate;
}
public void Execute(object parameter)
{
_executeDelegate(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
{
get
{
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;

#endregion
}


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.

License

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


Written By
President
India India
Did you like his post?

Oh, lets go a bit further to know him better.
Visit his Website : www.abhisheksur.com 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.
http://bit.ly/EXPERTCookBook

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 abhi2434@yahoo.com

Want a Coder like him for your project?
Drop him a mail to contact@abhisheksur.com

Visit His Blog

Dotnet Tricks and Tips



Dont forget to vote or share your comments about his Writing

Comments and Discussions

 
GeneralThanks Abhishek it helps me.+5 Pin
Algorithm_Seeker29-Jul-11 23:54
Algorithm_Seeker29-Jul-11 23:54 
GeneralReason for my vote of 2 Your title is misleading. Silverligh... Pin
Graeme_Grant20-Mar-11 12:49
mvaGraeme_Grant20-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.