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.
So to my understanding in MVVM
The View-->Sound and Animation
The ViewModel-->If some value is true, i would like to play the Sound and Animation on the 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.
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();
}
}
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.
}
}
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.
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.
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.
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.
Hope this helps a bit?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With