1, View可以通过DataContext访问ViewModel
除了Binding以外,在一些Event触发的时候,在behind code里用这种方法,直接访问ViewModel。
2, ViewModel访问View
直接设定一个View接口的成员变量,在创建ViewModel的时候,将View设置到该成员变量上。
但这么做不好,(But doing this we would be breaking the sanctity of MVVM.)
3, WPF - Attached behaviors (Closing View from ViewModel)
http://www.shujaat.net/2010/08/attached-behaviors.html
建一个project,copy网页里的代码很容易实现。
简单总结下: (利用附加属性和依赖属性来实现的)
- 在ViewModel类中创建一个依赖属性:IsClose。在RelayCommand中执行的时候,仅仅修改IsClose=true,并不去实现关闭窗口(不去操作Window)。
- 创建一个WindowAttachedBehavior类,该类会定义一个IsCloseView的附加属性。当这个属性的变化成true的时候,会实现关闭窗口(它负责操作Window)。(注意该类中的属性和方法都是静态的)
- 在View里用下面的方式绑定ViewModel的依赖属性IsClose,并触发附加属性IsCloseView的变化。实现了窗口的关闭,并解耦了ViewMode和View。
<Style>
<Style.Triggers>
<DataTrigger Binding="{Binding IsClose}" Value="true">
<Setter Property="local:WindowAttachedBehavior.IsCloseView" Value="true" />
</DataTrigger>
</Style.Triggers>
</Style>