假设我想使用事件在视图模型中调用命令。这是不好的做法吗?如果可以,为什么?
例子:
后台代码
void button1_Click(object sender, MouseEventArgs e)
{
this.ViewModel.OnButton1Click();
}
视图模型
void OnButton1Click()
{
// Do something
}
提前致谢。
是的,这是不好的做法,因为您直接引用的ViewModel
from,View
这意味着View
和之间的依赖关系ViewModel
,因此紧密耦合。
该模式特别要求View
NOT必须依赖于特定的ViewModel
实例或类型。这里的想法是分离的,Views
并且ViewModels
是多态的Views
(可以以多种方式显示相同数据的想法)。为了使您View
可重用,它不需要对特定ViewModel
类型有具体的依赖性。
Commands
如Kamel所说,更好的解决方法是使用。但是,并非所有事件/交互/控件都必须允许Commands
被调用。但是,您可以Commands
使用System.Windows.Interactivity.dll
随附的程序集附加到特定事件Blend SDK
。
这使您可以创建如下所示的XAML:
<i:Interaction.Triggers>
<i:EventTrigger EventName="LostFocus">
<i:InvokeCommandAction
Command="{Binding UpdateTextBoxBindingOnEnterCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type TextBox}}}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
..允许与事件处理程序使用相同的功能来调用Command
,但以对MVVM友好的方式分离。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句