【问题标题】:MVVM handling the Drag events of MouseDragElementBehaviorMVVM 处理 MouseDragElementBehavior 的拖动事件
【发布时间】:2012-04-01 21:24:47
【问题描述】:

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

所以我想我想做的是:

  • 编写一个继承自MouseDragElementBehavior 的行为
  • 覆盖OnAttached 方法
  • 订阅DragFinished 事件...但我不知道执行此操作的代码。

请帮忙! :)

【问题讨论】:

    标签: c# wpf behavior eventtrigger attachedbehaviors


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多