0

I'm making a music player in C# WPF. Files are added to a ListBox which works as the playlist for the MediaElement. In order to only show the filename without path and extension in the ListBox, I made a Song class which has properties for path and title.

What I can't figure out is how to set the MediaElements source to the path property of the Song object, so that I can just click an item in the ListBox and it would start playing.

Here's the code I use for adding files to the listbox:

        if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            foreach (string file in ofd.FileNames)
            {
                Song songs = new Song(System.IO.Path.GetFileNameWithoutExtension(file), file);
                listBox.Items.Add(songs);                                                                           
            }  
        }
H.B.
  • 166,899
  • 29
  • 327
  • 400
spex
  • 15
  • 1
  • 4

1 Answers1

0

Store the path in your Song class as well as just the filename. Then when you select the item you have the path immediately available to you. You can have as many properties on the Song class as you like. Just use the DisplayMemberPath property to control what gets displayed and the SelectedValuePath property to control what aspect of the item you need to return to the code. In this case you could use the filename as the DisplayMemberPath and the path as the SelectedValuePath.

You don't really need to store just the filename as you can pass the path through a converter to extract the filename for display. Obviously there would be a processing overhead for this and the extra memory storing the filename would take isn't really an issue, but I thought it was worth a mention.

ChrisF
  • 134,786
  • 31
  • 255
  • 325