SL4/MVVM:在 VM 中使用 void Foo() 处理 MouseDragElementBehavior.Dragging 事件 [英] SL4/MVVM: Handle MouseDragElementBehavior.Dragging event with void Foo() in VM
问题描述
我正在尝试处理我拥有的控件上的 MouseDragElementBehavior.Dragging 事件.见 在这里了解我为什么要这样做的背景.
I am trying to handle the MouseDragElementBehavior.Dragging event on a control I have. See here for background on why I want to do this.
我无法连接此事件.从 XAML 中您可以看到我向用户控件添加了一个行为.然后我尝试通过 CallMethodAction EventTrigger 在行为上的 Dragging 事件中添加一个处理程序.
I am having trouble wiring up this event. From the XAML you can see I have added a behavior to the user control. Then I attempted to add a handler to the Dragging event on the behavior via the CallMethodAction EventTrigger.
<i:Interaction.Behaviors>
<ei:MouseDragElementBehavior ConstrainToParentBounds="True">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Dragging">
<ei:CallMethodAction MethodName="NotifyChildrenYouAreDragging" TargetObject="{Binding}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</ei:MouseDragElementBehavior>
</i:Interaction.Behaviors>
我尝试了以下方法签名但没有成功:
I have tried the following method signatures with no luck:
void NotifyChildrenYouAreDragging(){}
void NotifyChildrenYouAreDragging(object sender, EventArgs e){}
void NotifyChildrenYouAreDragging(object sender, MouseEventArgs e){}
有人有使用触发器来处理附加行为中的事件的经验吗?
Anyone have experience using triggers to handle events in attached behaviors?
推荐答案
问题是 EventTrigger 没有连接到 Behavior 的事件.相反,它连接到 Behavior 的 AssociatedObject 事件.这是相关的源代码:
The problem is that the EventTrigger doesn't hook up to the Behavior's events. Instead it is hooking up to the Behavior's AssociatedObject's events. Here is the relevant source code:
protected override void OnAttached()
{
base.OnAttached();
DependencyObject associatedObject = base.AssociatedObject;
Behavior behavior = associatedObject as Behavior;
FrameworkElement element = associatedObject as FrameworkElement;
this.RegisterSourceChanged();
if (behavior != null)
{
associatedObject = ((IAttachedObject) behavior).AssociatedObject;
behavior.AssociatedObjectChanged += new EventHandler(this.OnBehaviorHostChanged);
}
....
}
所以你可以看到,如果触发器的关联对象是一个行为,那么它会将关联对象设置为行为的关联对象,也就是你的项目集合.项目集合没有拖动事件,因此不会触发任何事件.
So you can see that if the associated object of the trigger is a behavior, then it sets the associated object to the Behavior's associated object which is your items collection. The items collection doesn't have a dragging event so nothing is ever fired.
您可能可以通过创建另一个行为来获得您想要的结果,该行为检查关联的对象是否具有拖动行为,如果有,则将您的行为附加到拖动事件.然后从那里调用对象上的方法.
You could probably get the results you want by creating another behavior that checks to see if the associated object has a drag behavior and if so have your behavior attach to the dragging event. Then call the method on the object from there.
这篇关于SL4/MVVM:在 VM 中使用 void Foo() 处理 MouseDragElementBehavior.Dragging 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!