在ViewModel(这是它的DataContext)的视图中是否以对MVVM模式有害的任何方式的引用? [英] Is a reference in a View to a ViewModel (which is its DataContext) in any way detrimental to MVVM pattern?
问题描述
ViewModel
发布一个事件
和一个查看
它使用该虚拟机作为其$ DataContext
订阅该事件
,通过转换虚拟机的引用 DataContext
到VM实例: vm = DataContext作为MainViewModel;
if(vm == null)return;
vm.SomeUIRelatedNotice + = DoSomethingUIRelated;
我看到这一点,虚拟机崩溃,其可测试性没有受到影响,视图已经有一个虚拟机的引用,所以我看到没有任何问题,但我想听到MVVM纯粹主义者,如果他们认为这是坏的设计,对MVVM模式有负面影响,如果是这样为什么?
只要视图模型本身没有执行任何视图逻辑,我不认为这是打破MVVM模式。 >
在您的情况下,视图模型正在尝试以某种方式进行交互和指导视图,因此您应该知道有其他方法可以实现这种被认为是更纯粹的MVVM:
- MVVM Light Toolkit的
Messenger
服务 - Prism的
EventAggregator
或其交互模式
Let's say a ViewModel
publishes an Event
and a View
which is using that VM as its DataContext
subscribes to that Event
by obtaining a reference to the VM by casting its DataContext
to VM instance:
vm = DataContext as MainViewModel;
if (vm == null) return;
vm.SomeUIRelatedNotice += DoSomethingUIRelated;
The way I see this, the VM ramains decoupled and its testability is in no way affected, and the View already has a reference to the VM so I see no problem with this at all but I want to hear from the MVVM purists if they think this is bad design with negative impact on the MVVM pattern and if so why?
As long as the view model is not performing any view logic itself, I don't consider this to be breaking the MVVM pattern.
It looks like in your case the view model is trying to interact and direct the view somehow, so you should probably know that there are other ways to achieve such behavior which are considered to be more pure MVVM:
- MVVM Light Toolkit's
Messenger
service - Prism's
EventAggregator
or its interaction patterns
这篇关于在ViewModel(这是它的DataContext)的视图中是否以对MVVM模式有害的任何方式的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!