Click here to Skip to main content
14,606,456 members

Mouse Event Commands for MVVM

Rate this:
4.94 (18 votes)
Please Sign up or sign in to vote.
4.94 (18 votes)
22 Jan 2013CPOL
Use an Attached Property to execute an ICommand.


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);


    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? 


<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


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


About the Author

Matthew Searles
Software Developer Lovatts Publications
Australia Australia
No Biography provided

Comments and Discussions

AnswerRe: Garbage Collection? Pin
haindl12-May-15 2:15
Memberhaindl12-May-15 2:15 
GeneralRe: Garbage Collection? Pin
Matt Searles20-Jun-15 14:02
MemberMatt Searles20-Jun-15 14:02 

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.

Posted 17 Oct 2012

Tagged as


22 bookmarked