65.9K
CodeProject 正在变化。 阅读更多。
Home

MVVM 鼠标事件命令

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.95/5 (18投票s)

2012年10月18日

CPOL
viewsIcon

116178

downloadIcon

3233

使用附加属性来执行 ICommand。

引言

如果你想将 MouseEventArgs 传递到 ViewModel,这里有一个简洁的方法 Smile | <img src=

附加属性 

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

我们只需注册附加属性,挂钩 FrameworkElementMouseUp 事件,并在处理程序中调用 Command。很简单,对吧? 

用法 

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

当然,你不必使用 <Image>,任何框架元素都可以正常工作。这就是附加属性的优点! 

遇到问题,无法附加包含用于以 MVVM 风格处理任何鼠标事件的附加属性的源。但启动后,它包括 

  • MouseUp
  • MouseDown
  • MouseEnter
  • MouseLeave
  • MouseLeftButtonDown
  • MouseLeftButtonUp
  • MouseMove
  • MouseRightButtonDown
  • MouseRightButtonUp
  • MouseWheel
© . All rights reserved.