Reputation: 61
I am trying to develop a music player application in wp. Right now, I can retrieve the list of songs from the MediaLibrary and add it to a listbox.
MediaLibrary lib = new MediaLibrary();
var SongName = (from m in lib.Songs select m.Name).ToList();
listBox1.ItemsSource = SongName;
The list is getting populated and I am accessing the ListBox items using event
listBox1_SelectionChanged
I want the selected item to be converted to the type Song, so that i can play that using a MediaPlayer class.
normal typecasting such as
Song x = (Song)listBox1.SelectedItem;
How do I make it work?
Upvotes: 2
Views: 184
Reputation: 69372
You're selecting the song name (string) as the data source type. As you've seen, you can't convert a string to a Song
type simply by explicitly casting it (you could perform a search in the MediaLibrary
if you really wanted to keep the string type). Alternatively you can bind the Song
object itself to your ListBox.
MediaLibrary lib = new MediaLibrary();
var SongName = lib.Songs.ToList();
listBox1.ItemsSource = SongName;
Then in your event handler
Song x = listBox1.SelectedItem as Song;
if(x != null)
MediaPlayer.Play(x);
If you really want to only have the string
type in the ListBox
, you can perform a search like this in your SelectedChanged
event. (You'd have to make lib
a class level variable)
Song x = lib.Songs.Where(s => s.Name == listbox1.SelectedItem.ToString()).FirstOrDefault();
The main problem with this method is that if there are two tracks with the same name, only the first is returned. You'll need a way of differentiating them but the other properties, such as Artist
, has been removed from your data source (because you only used the Song's Name
property).
Upvotes: 1