Search code examples
c#wpflistboxmediaplaylist

Playing an item from a listbox


I'm trying to make my MediaPlayer play the item I click on the listbox.

But it's not working and I don't see why.

Here's the creation of my listbox: (I add the item when the open is executed)

    private void OpenExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        OpenFileDialog openFileDialog = new OpenFileDialog();
        openFileDialog.Filter = "Audio files (*.mp3;*.mpg;*.mpeg)|*.mp3;*.mpg;*.mpeg|Media files (*.avi;*.mp4;*.wmv)|*.avi;*.mp4;*.wmv|Image files (*.png;*.jpeg)|*.png;*.jpeg|All files (*.*)|*.*";
        if (openFileDialog.ShowDialog() == true)
            MediaPlayer.Source = new Uri(openFileDialog.FileName);
        MediaPlayer.Play();
        ListBoxItem item = new ListBoxItem();
        var name = openFileDialog.FileName;
        item.Content = name;
        playlist.Items.Add(item);
    }

And then here's the function when you double click on an item in the listbox:

    private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        MediaPlayer.Stop();
        MediaPlayer.Source = new Uri(playlist.SelectedItem.ToString());
        MediaPlayer.Play();
    }

Thanks for your help.


Solution

  • I think your playlist.SelectedItem.ToString() statement doesn't give a well formatted path. Try this instead:

    private void listBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        MediaPlayer.Stop();
        string mediaPath = ((ListBoxItem)playlist.SelectedValue).Content.ToString();
        MediaPlayer.Source = new Uri(mediaPath);
        MediaPlayer.Play();
    }
    

    To explain a little bit, your playlist.SelectedValue statement returns an object, that you have to cast to its original meaning which is ListBoxItem. Starting from this, you can then access your value path using Content property. Again, this is an object that you have to cast to its original meaning, which is a string (i.e: your string path).