MVVM handling the Drag events of MouseDragElementBehavior

試著忘記壹切 提交于 2019-12-22 12:54:27

问题


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:


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>


来源:https://stackoverflow.com/questions/9968489/mvvm-handling-the-drag-events-of-mousedragelementbehavior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!