ViewModel处理事件

时间:2013-08-05 09:05:52

标签: wpf mvvm

我在这里看到一个问题,OP询问有关将事件绑定到ViewModel的问题。基本上,ViewModel将重新呈现包含Model中必要数据的抽象View,以便View也可以使用Bindings。但是为了能够满足所有ViewModel还必须转换视图中发生的大多数用例,例如如果搜索文本框为空,则搜索按钮应显示为灰色。这很好,但我们可以在游戏中添加事件。如果Button.Click可以绑定到ViewModel中的EventHandler并且在事件处理程序中,那么你就可以使用模型对象了。

现在我的问题是,因为WPF支持事件驱动编程,为什么在ViewModel中处理不能发生的事件?我怎么能提供绑定事件功能?

2 个答案:

答案 0 :(得分:1)

事件处理程序将位于视图后面的代码文件中。如果您正在使用MVVM,那么您将希望最小化代码隐藏文件中的代码量。

WPF支持命令,ICommand界面包含CanExecuteExecute方法。有ICommand的实现允许在视图模型上实现这些方法。

话虽如此,指挥也有其局限性,所以you should consider using an MVVM framework when using MVVM。像Caliburn.Micro这样的东西附带Actions,它也允许根据控件事件调用视图模型上的动词。

答案 1 :(得分:1)

这是因为事件的使用明确地打破了MVVM模式(我相信你知道)。然而,还有另外一种方法 - 使用Attached Command Behaviour pattern。更多信息here

可以从here下载适用于附加命令的小而精彩框架的代码。

我希望这会有所帮助。


编辑。附加行为允许您在不破坏MVVM模式的情况下使用事件。用法就像

<Border Background="Yellow" Width="350" Margin="0,0,10,0" Height="35" CornerRadius="2" x:Name="test"> 
    <local:CommandBehaviorCollection.Behaviors>
        <local:BehaviorBinding Event="MouseLeftButtonDown" 
                               Action="{Binding DoSomething}" 
                               CommandParameter="An Action on MouseLeftButtonDown"/> 
        <local:BehaviorBinding Event="MouseRightButtonDown" 
                               Command="{Binding SomeCommand}" 
                               CommandParameter="A Command on MouseRightButtonDown"/>
    </local:CommandBehaviorCollection.Behaviors> 
    <TextBlock Text="MouseDown on this border to execute the command"/> 
</Border>
相关问题