MVVM模式违规:MediaElement.Play() [英] MVVM pattern violation: MediaElement.Play()
问题描述
我了解ViewModel不应该对View有任何了解,但是除了在ViewModel中引用View(或直接引用MediaElement)之外,如何从ViewModel调用MediaElement.Play()方法?
其他(链接的)问题:如何在不违反MVVM模式的情况下从ViewModel管理View控件的可见性?
I understand that ViewModel shouldn't have any knowledge of View, but how can I call MediaElement.Play() method from ViewModel, other than having a reference to View (or directly to MediaElement) in ViewModel?
Other (linked) question: how can I manage View's controls visibility from ViewModel without violating MVVM pattern?
推荐答案
1)不要从视图模型中调用Play()
.而是在视图模型中引发一个事件(例如PlayRequested
),然后在视图中侦听此事件:
1) Do not call Play()
from the view model. Raise an event in the view model instead (for instance PlayRequested
) and listen to this event in the view:
视图模型:
public event EventHandler PlayRequested;
...
if (this.PlayRequested != null)
{
this.PlayRequested(this, EventArgs.Empty);
}
视图:
ViewModel vm = new ViewModel();
this.DataContext = vm;
vm.PlayRequested += (sender, e) =>
{
this.myMediaElement.Play();
};
2)您可以在视图模型中公开一个布尔属性,并将控件的Visibility
属性绑定到该属性.由于Visibility
是类型Visibility
而不是bool
,因此您必须使用转换器.
2) You can expose in the view model a public boolean property, and bind the Visibility
property of your controls to this property. As Visibility
is of type Visibility
and not bool
, you'll have to use a converter.
您可以找到这种转换器的基本实现这里. 此相关问题可能也对您有帮助.
You can find a basic implementation of such a converter here. This related question might help you too.
这篇关于MVVM模式违规:MediaElement.Play()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!