开发者

How do I move to the next song using a MVVM mediaelement

开发者 https://www.devze.com 2023-04-08 04:49 出处:网络
I\'m learning C#/WPF/MVVM by building a simple media player. I am using ICollectionView in the MainViewModel for the playlist. I built a separate usercontrol for the mediaelement with some code-behind

I'm learning C#/WPF/MVVM by building a simple media player. I am using ICollectionView in the MainViewModel for the playlist. I built a separate usercontrol for the mediaelement with some code-behind to handle the volume, position, timeline (http://www.codeproject.com/KB/smart/RSSVideoReader.aspx). I know one of the goals of MVVM is to eliminate code-behind, but the WPF mediaelement is unique. I am now stuck 开发者_StackOverflow中文版trying to figure how to get the code-behind mediaelement's MediaEnded event to tell the MainViewModel's ICollectionView to MoveCurrentToNext.

This code fails:

MainViewModel

public void GoNext()
    {
        this.collectionView.MoveCurrentToNext();
    }

MyMediaElement.xaml.cs (Code behind)

private void mPlayDefault_MediaEnded(object sender, RoutedEventArgs e)
    {

        mPlayDefault.Stop();
        this.GoNext();            

    }

How do I get the MainViewModel to react to MyMediaElement's event? Thank You


This is the best I could come up with:

inside of the ViewModel:

public ICommand PlayCommand
{
  get
  {
    if (_playCommand == null) 
      _playCommand = new RelayCommand(player => this.play(player), param => this.canPlay); 
    return _playCommand;
  }
}
void play(object player)
{
  if (_player == null)
  {
    _player = (MediaElement)player;
    _player.MediaEnded += new RoutedEventHandler((s, e) =>
    {
      if (canPlayNext)
        playNext();
    });
  }

  _player.Play();  
}

...but I am still open for other ideas.


Daniel Pratt was correct (See Comments). Using Interaction.Triggers worked as I had hoped. I ran into a problem with the expressions dll and was totally frustrated. Downloading the dll directly from codeplex and unblocking it solved the problem. Many thanks to Daniel and Stackoverflow.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号