我知道 ViewModel 不应该了解 View,但是除了在 ViewModel 中引用 View(或直接 MediaElement)之外,如何从 ViewModel 调用 MediaElement.Play() 方法?
其他(链接)问题:如何在不违反 MVVM 模式的情况下管理 ViewModel 中的 View 控件可见性?
最佳答案
1) 不要从 View 模型调用Play()
。相反,在 View 模型中引发一个事件(例如 PlayRequested
)并在 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) 您可以在 View 模型中公开一个公共(public) bool 属性,并将控件的 Visibility
属性绑定(bind)到该属性。由于 Visibility
的类型为 Visibility
而不是 bool
,因此您必须使用转换器。
您可以找到此类转换器的基本实现 here 。 这个related question也可能对你有帮助。
关于wpf - MVVM 模式违规 : MediaElement. Play(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10631748/