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);
}
}
Store the path in your
Songclass 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 theSongclass as you like. Just use theDisplayMemberPathproperty to control what gets displayed and theSelectedValuePathproperty to control what aspect of the item you need to return to the code. In this case you could use the filename as theDisplayMemberPathand the path as theSelectedValuePath.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.