views:

110

answers:

2

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.

A: 

I would think the structure would look something like...

Model -> Object containing sound and video/bitmaps

View -> Visual Control for containing the Storyboard

ViewModel -> Controller for handling animation events

I haven't delved too far into WPF animation but, from what I have seen you need to have a pretty close relationship between the UIElements and the Controller. Where MVVM excels is its separations of the logic layer from the presentation layer, this may cause you a fair amount of pain. Instead of using MVVM you might want to look at the MVC pattern which has a closer relationship between the View and the Controller.

Agies
+1  A: 

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?

Brian Genisio