2012-06-14 49 views
2

我正在寻找一个关于如何使用Prism实现事件聚合器的好例子(阅读:简单)。我从来没有使用Prism,而且我对MVVM本身也很陌生。MVVM查看事件Viewmodel命令绑定

我有一个WPF画布作为视图,我想处理ViewModel画布上的MouseUp事件。现在,我们组织的权力要求我使用Prism,显然Prism建议使用事件聚合器,这就是为什么我需要一个样本才能让我开始。

回答

4

所有您需要的是来自MVVMLight或System.Windows.Interactivity(Blend SDK)的EventToCommand行为。我建议你采取MVVMLight版本,因为它有一些有用的特价:)从棱镜

<Canvas> 
<i:Interaction.Triggers> 
    <i:EventTrigger EventName="MouseUp" > 
     <i:InvokeCommandAction Command="{Binding YourMouseUpViewModelCommand}" /> 
    </i:EventTrigger> 
</i:Interaction.Triggers> 
</Canvas> 

EventAggregator我主要用于分离视图模型视图模型来沟通。

1

我不知道PRISM的EventAggregator允许使用event-> command binding。

这种情况下的另一种选择是使用“行为”。这里有一个体面的概述行为:http://wpftutorial.net/Behaviors.html。你可以忽略教程的Blend部分;重要的是你至少安装了Blend 3 SDK。以下是我这样做:

public class ButtonDoubleClickCommandBehavior : Behavior<Button> 
{ 
    public ICommand DoubleClickCommand 
    { 
     get { return (ICommand)GetValue(DoubleClickCommandProperty); } 
     set { SetValue(DoubleClickCommandProperty, value); } 
    } 

    public static readonly DependencyProperty DoubleClickCommandProperty = 
     DependencyProperty.Register("DoubleClickCommand", typeof(ICommand), typeof(ButtonDoubleClickCommandBehavior)); 

    protected override void OnAttached() 
    { 
     this.AssociatedObject.MouseDoubleClick += AssociatedObject_MouseDoubleClick; 
    } 

    protected override void OnDetaching() 
    { 
     if (this.AssociatedObject != null) 
     { 
      this.AssociatedObject.MouseDoubleClick -= AssociatedObject_MouseDoubleClick; 
     } 
    } 

    void AssociatedObject_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
    { 
     if (DoubleClickCommand != null && DoubleClickCommand.CanExecute(null)) 
     { 
      DoubleClickCommand.Execute(null); 
     } 
    } 
} 

您能再依赖属性添加到行为绑定命令参数,以便您可以执行与该参数的命令;我在我的例子中使用了null。

我的XAML:

<Button Content="{Binding Path=Description}" VerticalAlignment="Center" HorizontalAlignment="Stretch" Template="{StaticResource TextBlockButtonTemplate}" Style="{StaticResource ZynCommandButton}" Tag="DescriptionButton"> 
    <e:Interaction.Behaviors> 
     <ZViewModels:ButtonDoubleClickCommandBehavior DoubleClickCommand="{Binding Path=ItemDescriptionCommand}"/> 
    </e:Interaction.Behaviors> 
</Button> 
0

使用行为一个更通用的方法,提出了在AttachedCommandBehavior V2 aka ACB它甚至还支持多种事件到命令绑定,

这里使用一个很简单的例子:

<Border local:CommandBehavior.Event="MouseDown" 
     local:CommandBehavior.Command="{Binding DoSomething}" 
     local:CommandBehavior.CommandParameter="From the DarkSalmon Border" 
/>