简体   繁体   English

wp7音乐播放器

[英]wp7 music player

I am trying to develop a music player application in wp. 我正在尝试在wp中开发音乐播放器应用程序。 Right now, I can retrieve the list of songs from the MediaLibrary and add it to a listbox. 现在,我可以从MediaLibrary中检索歌曲列表并将其添加到列表框中。

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 该列表正在填充,我正在使用事件访问ListBox项

listBox1_SelectionChanged 

I want the selected item to be converted to the type Song, so that i can play that using a MediaPlayer class. 我希望将所选项目转换为Song类型,以便可以使用MediaPlayer类播放该项目。

normal typecasting such as 正常的类型转换,例如

Song x = (Song)listBox1.SelectedItem;

How do I make it work? 我该如何运作?

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). 如您所见,您不能仅通过显式转换字符串就将其转换为Song类型(如果您确实想保留字符串类型,则可以在MediaLibrary执行搜索)。 Alternatively you can bind the Song object itself to your ListBox. 另外,您可以将Song对象本身绑定到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. 如果您确实只想在ListBox使用string类型,则可以在SelectedChanged事件中执行类似的搜索。 (You'd have to make lib a class level variable) (您必须将lib设为类级变量)

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). 您需要一种区分它们的方法,但是其他属性(例如Artist已从数据源中删除(因为您仅使用了Song's Name属性)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM