MVVM处理MouseDragElementBehavior的Drag事件

时间:2012-04-01 21:24:47

标签: c# wpf behavior eventtrigger attachedbehaviors

This question告诉我在单词中做什么,但我无法弄清楚如何编写代码。 :)

我想这样做:

<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不起作用......我认为这是因为它希望在DragFinished而不是SomeUIElement上找到MouseDragElementBehavior事件。这是对的吗?

所以我认为我想要做的是:

  • 编写一个继承自MouseDragElementBehavior
  • 的行为
  • 覆盖OnAttached方法
  • 订阅DragFinished活动...但我无法弄清楚这一点的代码。

请帮忙! :)

1 个答案:

答案 0 :(得分: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>