2

这个问题用文字告诉我该怎么做,但我不知道如何编写代码。:)

我想做这个:

<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事件...但我无法弄清楚执行此操作的代码。

请帮忙!:)

4

1 回答 1

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>
于 2012-10-09T05:04:40.540 回答