我评论为UWP开发C#应用程序,我是新手,我愿意用他的专辑和艺术家展示歌曲列表,我已经完成了ListView与(ListView.items.add)一起使用它们的属性,但这根本不是美学。 绑定是可能的?你能帮帮我吗?
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
this.DataContext = this;
StorageFolder storageFolder = KnownFolders.MusicLibrary;
var files = await storageFolder.GetFilesAsync();
foreach (var file in files)
{
var musicProperties = await file.Properties.GetMusicPropertiesAsync();
var Artista = musicProperties.Artist;
if (Artista == "")
{
Artista = "Artista desconocido";
}
string fileName = file.DisplayName;
listView.Items.Add(file.DisplayName + "-" + Artista );
}
}
答案 0 :(得分:1)
可以用?
绑定
是的,绑定是可能的,我认为绑定是一种比在后面的代码中向ListView
添加项目更好的方法,你应该能够使用DataTemplate
来构建每个项目的结构并使用ObservableCollection Class在项目添加,删除或刷新时提供通知。
例如:
<ListView ItemsSource="{x:Bind MusicList}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="File Name: " />
<TextBlock Text="{Binding FileName}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Artist: " />
<TextBlock Text="{Binding Artist}" />
</StackPanel>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Album: " />
<TextBlock Text="{Binding Album}" />
</StackPanel>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
您需要为这些“FileName”,“Artist”和“Album”属性创建数据模型类:
public class MusicLib
{
public string FileName { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
}
代码背后的代码:
private ObservableCollection<MusicLib> MusicList = new ObservableCollection<MusicLib>();
public MainPage()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
StorageFolder musicLib = KnownFolders.MusicLibrary;
var files = await musicLib.GetFilesAsync();
foreach (var file in files)
{
var musicProperties = await file.Properties.GetMusicPropertiesAsync();
var artist = musicProperties.Artist;
if (artist == "")
artist = "Artista desconocido";
var album = musicProperties.Album;
if (album == "")
album = "Unkown";
MusicList.Add(new MusicLib { FileName = file.DisplayName, Artist = artist, Album = album });
}
}
我使用您的方法在此处将空的“艺术家”和“相册”属性设置为特定值,但您也可以使用Converter
执行此项工作,有关使用Converter
的信息,您可以参考IValueConverter interface,此文档中有示例。
顺便说一句,如果您想要访问应用中的音乐库,则需要在“Package.appxmanifest”文件中启用“音乐库”功能。