我正在开发Windows应用商店应用。我有这样的XML:
<?xml version="1.0" encoding="utf-8" ?>
<music>
<singer>
<name>Coldplay</name>
<song>Scientist</song>
<lyrics>lol lalala</lyrics>
</singer>
<singer>
<name>Coldplay</name>
<song>test2</song>
<lyrics>lol lalala2</lyrics>
</singer>
<singer>
<name>another</name>
<song>şarkı</song>
<lyrics>lol lalala3</lyrics>
</singer>
</music>
在C#代码中,“lvSingers”是我的列表视图。我把歌手的名字绑在那里。
private void Page_Loaded(object sender, RoutedEventArgs e)
{
string musicXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "Assets/test.xml");
XDocument loadedData = XDocument.Load(musicXMLPath);
var data = from query in loadedData.Descendants("singer")
select new Singer
{
name = (string)query.Element("name"),
song = (string)query.Element("song"),
akor = (string)query.Element("lyrics")
};
lvSingers.ItemsSource = data;
}
}
当我运行此代码时,我会收到多个歌手名字,我想避免这样做。例如:
Coldplay
Coldplay
another
我只想在那里只有一个酷玩乐队。我想要的是不同的输出。 非常感谢您的反馈和帮助。此致...
答案 0 :(得分:1)
我离开了我的win8开发机器。我不确定listview如何处理分组。您可以尝试以下方法。
var data = from query in loadedData.Descendants("singer")
select new Singer
{
name = (string)query.Element("name"),
song = (string)query.Element("song"),
akor = (string)query.Element("lyrics")
}.GroupBy(ex => ex.name);
根据您的需要,您可能只想向listview发送一个仅包含名称的数据源。
lvSingers.ItemsSource = data.Select(ex => (string)ex.name).Distinct();
答案 1 :(得分:1)
问题在于,即使重复了艺术家名称,您也会有不同的项目,因为Coldplay的歌曲不同。因此,您可以将ItemsSource绑定到不同的列表,并使用以下内容设置SelectedArtist属性:
XDocument doc = XDocument.Load("Music.xml");
var data = doc.Descendants("singer").Select(x => new Singer {
Name = (string)x.Element("name"),
Song = (string)x.Element("song"),
Lyrics = (string)x.Element("lyrics")
});
List<string> dataToBind = data.Select(x => x.Name).Distinct().ToList();