【发布时间】:2011-09-19 06:23:25
【问题描述】:
在文章WPF Apps With The Model-View-ViewModel Design Pattern,作者Josh Smith说:
(1) 在设计良好的 MVVM 架构中,大多数视图的代码隐藏应该是空的,或者最多只包含操作该视图中包含的控件和资源的代码。 (2) 有时还需要在 View 的代码隐藏中编写与 ViewModel 对象交互的代码,例如挂钩事件或调用原本很难从 ViewModel 本身调用的方法。
我的问题是,在(1)处,为什么空的代码隐藏被认为是一个设计良好的 MVVM。(听起来空的代码隐藏总是好的。)
编辑:我的问题如下,为什么像AttachedCommandBehavior 或InvokeCommandAction 这样的方法试图避免代码隐藏编码。
让我更详细地解释一下。
就(1)而言,我认为来自AttachedCommandBehavior的情况如下。由于 Border 没有为 MouseRightButtonDown 实现 ICommandSource,因此您通常无法绑定事件和 ICommand,但可以使用 AttachedCommandBehavior。
<!-- I modified some code from the AttachedCommandBehavior to show more simply -->
<Border>
<local:CommandBehaviorCollection.Behaviors>
<local:BehaviorBinding Event="MouseRightButtonDown"
Command="{Binding SomeCommand}"
CommandParameter="A Command on MouseRightButtonDown"/>
</local:CommandBehaviorCollection.Behaviors>
</Border>
或
我们可以使用System.Windows.Interactivity.InvokeCommandAction 来做到这一点。
<Border xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseRightButtonDown">
<i:InvokeCommandAction Command="{Binding SomeCommand}"
CommandParameter="A Command on MouseRightButtonDown"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Border>
但是,
我们使用以下 XAML 及其具有 Border_MouseRightButtonDown 方法的代码隐藏,该方法链接到上述 (2) Josh Simth。
<Border MouseRightButtonDown ="Border_MouseRightButtonDown"/>
我认为使用上面的代码隐藏还不错,因为它们之间的区别仅在于绑定命令或添加事件处理程序的位置。
您对此有何看法?
【问题讨论】:
-
我认为,如果 Border_MouseRightButtonDown 不触发视图模型上的任何操作,并且不修改它的状态,那是完全可以的。在 ViewModel 中放置大量 UI 代码最终会将后面的代码转移到 ViewModel。
标签: xaml mvvm code-behind