2012-04-01 75 views
2

This question告訴我該怎麼做,但我無法弄清楚如何編寫代碼。 :)MVVM處理MouseDragElementBehavior的Drag事件

我想這樣做:

<SomeUIElement> 
    <i:Interaction.Behaviors> 
     <ei:MouseDragElementBehavior ConstrainToParentBounds="True"> 
      <i:Interaction.Triggers> 
       <i:EventTrigger EventName="DragFinished"> 
        <i:InvokeCommandAction Command="{Binding SomeCommand}"/> 
       </i:EventTrigger> 
      </i:Interaction.Triggers> 
     </ei:MouseDragElementBehavior> 
    </i:Interaction.Behaviors> 
</SomeUIElement> 

但隨着其他問題概述,該EventTrigger不能正常工作......我認爲這是因爲它要找到在SomeUIElement而不是DragFinished事件的MouseDragElementBehavior。那是對的嗎?

所以我覺得我想要做的是:

  • 編寫從MouseDragElementBehavior
  • 覆蓋的OnAttached方法
  • 訂閱DragFinished事件......繼承的行爲,但我不能找出執行此操作的代碼。

請幫忙! :)

回答

1

這是我爲了解決你的問題:

public class MouseDragCustomBehavior : MouseDragElementBehavior 
{ 
    public static DependencyProperty CommandProperty = 
     DependencyProperty.Register("Command", typeof(ICommand), typeof(MouseDragCustomBehavior)); 

    public static DependencyProperty CommandParameterProperty = 
     DependencyProperty.Register("CommandParameter", typeof(object), typeof(MouseDragCustomBehavior)); 

    protected override void OnAttached() 
    { 
     base.OnAttached(); 

     if (!DesignerProperties.GetIsInDesignMode(this)) 
     { 
      base.DragFinished += MouseDragCustomBehavior_DragFinished; 
     } 
    } 

    private void MouseDragCustomBehavior_DragFinished(object sender, MouseEventArgs e) 
    { 
     var command = this.Command; 
     var param = this.CommandParameter; 

     if (command != null && command.CanExecute(param)) 
     { 
      command.Execute(param); 
     } 
    } 

    protected override void OnDetaching() 
    { 
     base.OnDetaching(); 
     base.DragFinished -= MouseDragCustomBehavior_DragFinished; 
    } 

    public ICommand Command 
    { 
     get { return (ICommand)GetValue(CommandProperty); } 
     set { SetValue(CommandProperty, value); } 
    } 

    public object CommandParameter 
    { 
     get { return GetValue(CommandParameterProperty); } 
     set { SetValue(CommandParameterProperty, value); } 
    } 
} 

然後將XAML來稱呼它....

 <Interactivity:Interaction.Behaviors> 
      <Controls:MouseDragCustomBehavior Command="{Binding DoCommand}" /> 
     </Interactivity:Interaction.Behaviors>