WPF MouseDown / MouseUp Command

Maybe you wanted to bind a command to the MouseDown Event of the Button.
But there is just the Command for the Click Event. Therefore it is necessary to do a little bit of coding.

I usually need the MouseDown / MouseUp Events of the Button for several use cases.
Therefore I just created a simple behavior which contains two command properties (on for the MouseUp and one for the MouseDown event).

The MouseCommandBehavior class looks like this

public static class MouseCommandBehavior
  {
    #region Commands

    ///
    /// The comamnd which should be executed when the mouse is down
    ///
    public static readonly DependencyProperty MouseDownCommandProperty =
        DependencyProperty.RegisterAttached("MouseDownCommand",
            typeof(ICommand),
            typeof(MouseCommandBehavior),
            new FrameworkPropertyMetadata(null, (obj, e) => OnMouseCommandChanged(obj, (ICommand)e.NewValue, false)));

    ///
    /// Gets the MouseDownCommand property
    ///
    public static ICommand GetMouseDownCommand(DependencyObject d)
    {
      return (ICommand)d.GetValue(MouseDownCommandProperty);
    }

    ///
    /// Sets the MouseDownCommand property
    ///
    public static void SetMouseDownCommand(DependencyObject d, ICommand value)
    {
      d.SetValue(MouseDownCommandProperty, value);
    }

    ///
    /// The comamnd which should be executed when the mouse is up
    ///
    public static readonly DependencyProperty MouseUpCommandProperty =
        DependencyProperty.RegisterAttached("MouseUpCommand",
            typeof(ICommand),
            typeof(MouseCommandBehavior),
            new FrameworkPropertyMetadata(null, new PropertyChangedCallback((obj, e) => OnMouseCommandChanged(obj, (ICommand)e.NewValue, true))));

    ///
    /// Gets the MouseUpCommand property
    ///
    public static ICommand GetMouseUpCommand(DependencyObject d)
    {
      return (ICommand)d.GetValue(MouseUpCommandProperty);
    }

    ///
    /// Sets the MouseUpCommand property
    ///
    public static void SetMouseUpCommand(DependencyObject d, ICommand value)
    {
      d.SetValue(MouseUpCommandProperty, value);
    }

    #endregion

    ///
    /// Registeres the event and calls the command when it gets fired
    ///
    private static void OnMouseCommandChanged(DependencyObject d, ICommand command, bool isMouseUp)
    {
      if (command == null) return;

      var element = (FrameworkElement)d;

      if(isMouseUp)
          element.PreviewMouseUp += (obj, e) => command.Execute(null);
      else
          element.PreviewMouseDown += (obj, e) => command.Execute(null);
      }
    }
  }

I hardcoded in this class these two events. But you could even add your own ones :)

In the XAML-Code you can use it like that

        <button>

If you want a even more flexible approach where you can register just one Command then you can use the behavior of Sacha Barber.
Check this out WPF : Attached Commands

I attached a zip file (remove the .doc extension) which contains a complete project. It is slightly different then what I explained above but the idea is the same.

WpfApplication2.zip

Advertisement
    • Elad Gutman
    • March 9th, 2011

    Hi,

    This is a great example, and just what I was looking for… so thanks!

    However, two problems that I saw:

    1) There is a compilation error in MouseCommandBehavior.OnMouseCommandChanged: “The name ‘routedEventName’ does not exist in the current context”.
    2) I have omitted this line and compilation is OK, but the application is not working, and nothing is happening when clikcing the ‘Click me’ button. I have also set a breakpoint in the ‘OnMouseCommandChanged’ method, but I never reches there.

    Here is how my xaml looks like:

    As you can see, all I did was adding a button to a grid, and set a binding to the ‘MouseDownCommand’ and ‘MouseUpCommand’ properties. In the xaml.cs file the constructor of Window1 looks like this:

    public Window1()
    {
    InitializeComponent();
    mMyCommand = new MyCommand();
    DataContext = this;
    }

    Any clue what am I missing in order to make this example fully compiled and working?

    Thanks again,

    Elad

    • Elad Gutman
    • March 9th, 2011

    For some reason the xaml was not published:

    • Elad Gutman
    • March 10th, 2011

    Hi,

    This is exactly the example I was looking for, so thanks a lot for the snippet.

    However, two problems I have:
    1) I have a compilation error in the ‘OnMouseCommandChanged’ method – the routeEventName is not recognized by the compiler. Once I have remarked this line compilation is completed successfully.

    2) Once I am running the application with the xaml example you gave, nothing is happening in the button when clicking it. I even tried adding a breakpoint in the OnMouseCommandChanged method, but I don’t reach there.

    This is how the xaml looks like:

    And when more thing, in the constructor of the main window I have set ‘DataContext = this’.

    Am I missing something here? Any chance you can give a full example?

    Thanks again,

    Elad

      • michlG
      • March 10th, 2011

      Hi,

      sorry for the slow reply but I was not online yesterday.

      The problem is that I had a working version (the file attached on the bottom) then I modified it a bit for the blog. But the modifications introduced this bug :)
      Just download the file and extract it.

      Have fun!
      Michael

    • Elad Gutman
    • March 28th, 2011

    Michael,

    I’m terribly sorry for my late respond…

    I have downloaded the sample and it’s working now. However, I still need to find some time to analyze it and understand what you did. Since I’m new to WPF things are a little bit slow for me… :)

    I’ll write soon.

    Elad

  1. Found best multi event command binder in codeplex

    Multi Event Command Binder

    Benefits:

    1:Ability to bind multiple event to multiple commands.
    2:In CommandArgs in command handler you can even get original event args this was not possible with existing command binders.
    3:In CommandArgs in command handler you can even get original source of the event this was not possible with existing command binders.
    4:In this you can control individual CanExecute methods.

    Blogs
    Multi Event Command BlogSpot
    Multi Event Command WordPress

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.