CommandProxy: Howto databind a ICommand to an InputBinding

When you start using the ViewModel pattern in WPF, some day you stumble upon that it is not possible to databind an command to an MouseBinding or KeyBinding.

So why this is not possible?

The WPF DataBinding’s are heavily based on DependencyPropertys which are only work on objects which inherit from DependencyObject. But the Command property on Mouse- and KeyBinding isnt an DependencyProperty. So DataBinding will not work on them.

The next problem is that the InputBinding class is only derived from DependencyObject and so it has no inheritance context which allow to get access to DataContext and ElementName.

May it is a performance consideration, may it is mistake, finally i dont know why they make this decision.

So how to make the DataBinding work anyway?

My solution is called CommandProxy and it uses a simpified version of Josh Smith Virtual Branch technic.

So here the CommandProxy looks like:

    public class CommandProxy : Freezable, ICommand
        protected override Freezable CreateInstanceCore()
            return new CommandProxy();

        public static readonly DependencyProperty CommandProperty =
            DependencyProperty.Register( "Command",
                new UIPropertyMetadata() );

        public ICommand Command
            get { return (ICommand)GetValue( CommandProperty ); }
            set { SetValue( CommandProperty, value ); }

        public void Execute( object parameter )
            Command.Execute( parameter );

        public bool CanExecute( object parameter )
            return Command != null && Command.CanExecute( parameter );

        public event EventHandler CanExecuteChanged
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }

And here is how to use it:

    <Grid Background="LightGreen">


            <a:CommandProxy x:Key="TestCommand"
                    Command="{Binding TestCommand}" />



            <MouseBinding Command="{StaticResource TestCommand}" Gesture="LeftClick" />


        <TextBlock Text="click here" VerticalAlignment="Center" TextAlignment="Center" />


As the name suggests, all this class dose is to expose a ICommand interface and redirect its methods to the databound command. The inheritance context problem is resolve by inherting from Freezable. You can read more about why Freezable helps here, in Dr. WPFs Blog here.

Download the CommandProxySample Visual Studio 2008 Solution.

2 thoughts on “CommandProxy: Howto databind a ICommand to an InputBinding”

  1. Hi Steve,
    thank you very much! Great post! You saved a lot of my time!

    Your solution is very nice, easy, short. Your article is clear.

    Many thanks!

Comments are closed.