MVVM 模式违规:MediaElement.Play() [英] MVVM pattern violation: MediaElement.Play()

查看:17
本文介绍了MVVM 模式违规: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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆