65.9K
CodeProject is changing. Read more.
Home

Mouse Event Commands for MVVM

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.95/5 (18 votes)

Oct 18, 2012

CPOL
viewsIcon

114203

downloadIcon

3201

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