Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Mouse Event Commands for MVVM

0.00/5 (No votes)
22 Jan 2013 3  
Use an Attached Property to execute an ICommand.

Introduction

If you ever want to pass MouseEventArgs to a ViewModel, here's a neat way to do it Smile | <img src=

The Attached Property 

public class MouseBehaviour
{
    public static readonly DependencyProperty MouseUpCommandProperty =
        DependencyProperty.RegisterAttached("MouseUpCommand", typeof(ICommand), 
        typeof(MouseBehaviour), new FrameworkPropertyMetadata(
        new PropertyChangedCallback(MouseUpCommandChanged)));

    private static void MouseUpCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)d;

        element.MouseUp += new MouseButtonEventHandler(element_MouseUp);
    }

    static void element_MouseUp(object sender, MouseButtonEventArgs e)
    {
        FrameworkElement element = (FrameworkElement)sender;

        ICommand command = GetMouseUpCommand(element);

        command.Execute(e);
    }

    public static void SetMouseUpCommand(UIElement element, ICommand value)
    {
        element.SetValue(MouseUpCommandProperty, value);
    }

    public static ICommand GetMouseUpCommand(UIElement element)
    {
        return (ICommand) element.GetValue(MouseUpCommandProperty);
    }
}

We simply register the attached property, hook the MouseUp event for the FrameworkElement, and invoke the Command in the handler. Simple enough, right? 

Usage 

<Image Source="c:/temp.png" [Your xmlns]:MouseBehaviour.MouseUpCommand="{Binding MouseUpCommand}"></Image>

You do not, of course, have to use an <Image>, any framework element will work just fine. That's the beauty of Attached Properties! 

Having trouble attaching source, which contains Attached Properties for handling any mouse event MVVM style. But when it's up, includes 

  • MouseUp
  • MouseDown
  • MouseEnter
  • MouseLeave
  • MouseLeftButtonDown
  • MouseLeftButtonUp
  • MouseMove
  • MouseRightButtonDown
  • MouseRightButtonUp
  • MouseWheel

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here