如何在MVVM中播放声音和动画 [英] How to play Sound and Animations in MVVM
问题描述
我已经阅读了很多有关播放声音/动画的最佳方法的博客,但如果可能的话,我希望看到一个简化的示例,以了解如何做到这一点,以便我更好地理解.
I have read alot of blogs about the best way to play sound/Animation but if possible I would like to see a simplified example on how this is done so I understand better.
所以我对MVVM的理解
So to my understanding in MVVM
视图->声音和动画
ViewModel->如果某些值为true,我想在视图上播放声音和动画.
The ViewModel-->If some value is true, i would like to play the Sound and Animation on the view.
现在我该怎么做.有人告诉我使用ISoundService和IAnimationService之类的接口.在View中实施,然后做什么?如果可能的话,一个可行的裸露示例将大有帮助.
Now How would I go about doing this. I was told to use interfaces like ISoundService and IAnimationService. Implement in the View and then do what? If possible, a workable bare bone example will help alot.
推荐答案
就声音而言,不一定是处理它的View.例如,我这样做是为了播放声音:
As far as sound goes, this isn't necessarily the View that handles it. For instance, I do something like this for playing a sound:
public interface IAudioPlayer
{
void Play(string fileName);
}
public class AudioPlayer : IAudioPlayer
{
private readonly SoundPlayer player = new SoundPlayer();
public void Play(string fileName)
{
player.Stream = File.OpenRead(fileName);
player.Play();
}
}
然后,我使用依赖注入将其传递到我的ViewModel中:
Then, I use Dependency Injection to pass it into my ViewModel:
public class TheViewModel
{
public TheViewModel(IAudioPlayer audioPlayer)
{
// probably store it as a private readonly field for later use.
}
}
另一种选择是让声音服务摆在那儿,监听ViewModel通过某些消息传递系统(例如EventAggregator)发送的事件.
Another option would be to have a sound service sitting out there, listening to events that the ViewModel sends through some messaging system... EventAggregator, for instance.
就动画而言,相同类型的方法可以起作用.通常,我在XAML的视图"中定义动画.然后,在View中,我侦听ViewModel触发的某种事件,以告知View执行该动画.
As far as Animation, the same types of approaches can work. Usually, I define the animation in the View in XAML. Then, in the View, I listen for some sort of event to be fired from the ViewModel to tell the View to execute that animation.
此外,在过去,我将数据绑定用于ViewModel中控制的双精度值,因此仍然存在一些可测试的行为来管理动画.
Also, in the past, I have used data binding to double values that are controlled in the ViewModel so there is still some testable behavior that manages the animation.
我使用的另一种方法是混合MVVM/MVP,其中ViewModel传递了一个IView接口,上面带有一个名为ExecuteDeletionAnimation的方法. ViewModel调用该方法,然后View实现该方法.
One other approach that I have used is a hybrid MVVM/MVP thing, where the ViewModel gets passed an IView interface with a method on it called ExecuteDeletionAnimation. The ViewModel calls the method, and the View implements the method.
希望这会有所帮助吗?
这篇关于如何在MVVM中播放声音和动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!