5

This question is not related to the MediaElement—pertaining to this, I’ve read both MediaElement.play() from within ViewModel and MVVM pattern violation: MediaElement.Play(), and I agree with both of them.

But say that we’re using instead a third-party assembly such as NAudio. We don’t have to find a way of plugging an existing XAML media control’s interactive features into our ViewModel. Instead, we can simply use, e.g., InteractionTriggers in our View, subscribe to it in our ViewModel, and invoke the play command on a given media file.

Now my question is: is this still something that fits, within the MVVM pattern, into the ViewModel? Or should we rather hand this down to the Model and play the file from there?

Informagic
  • 1,132
  • 1
  • 11
  • 23

1 Answers1

8

I would say it entirely depends on the nature of the media file and its relation to your app's core logic.

Is it just a UI feedback sound effect that gets played when you click on something? Stays in the view.

Is it a music player app that plays music from a playlist? That's core logic and belongs in the VM.

If I'm unsure where something lives, I think about an imaginary "view" on my app that uses a text console rather than WPF. If the logic still exists even if driven by a console, then it lives in the VM.

GazTheDestroyer
  • 20,722
  • 9
  • 70
  • 103
  • Thanks, I really like your console thought. But what you’re saying is that playing a media file does not happen in the Model, right? Well, thinking the console way, I guess it makes sense: playing the file is really presenting it, just not in a visual, but in an acoustic way. Wow, I really like the avenues your console thought opens! – Informagic Oct 05 '18 at 11:16
  • Think about a music player that is console driven. You still want it to play music, so yes, play the music from the view model. If a sound effect only plays because it's part of a particular whizzy GUI, then it stays with the GUI in the view. – GazTheDestroyer Oct 05 '18 at 11:24
  • 1
    Thanks again, this is absolutely convincing. Plus, I’ll make the console line of thought my own from now on, so thanks for that, too. – Informagic Oct 05 '18 at 11:26
  • MusicPlayerApp: I would implement an IMusicPlayService and hand it over to the ViewModel. The VM can decide when to play and the service will know how to play. – Sir Rufo Oct 05 '18 at 18:00