MVVM handling the Drag events of MouseDragElementB

2019-05-23 10:55发布

This question tells me what to do in words, but I can't figure out how to write the code. :)

I want to do this:

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

But as the other question outlines, the EventTrigger doesn't work... I think it's because it wants to find the DragFinished event on the SomeUIElement instead of on the MouseDragElementBehavior. Is that correct?

So I think what I want to do is:

  • Write a behavior that inherits from MouseDragElementBehavior
  • Override the OnAttached method
  • Subscribe to the DragFinished event... but I can't figure out the code to do this bit.

Help please! :)

1条回答
何必那么认真
2楼-- · 2019-05-23 11:57

Here is what I implemented to solve your problem :

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

And then the XAML to call it like this....

        <Interactivity:Interaction.Behaviors>
            <Controls:MouseDragCustomBehavior Command="{Binding DoCommand}" />
        </Interactivity:Interaction.Behaviors>
查看更多
登录 后发表回答