我是WPF
的新用户,我正在尝试使用MVVM
将目录中的歌曲绑定到数据网格。到目前为止,我已经能够使用“foreach循环”绑定一个歌曲文件,但我无法提出将显示其余歌曲的逻辑。以下是我到目前为止所做的事情:
using System.IO;
namespace MusicPlayer
{
public class MainWindowViewModel
{
public MainWindowViewModel()
{
Songs = GetSongs();
}
public Songs Songs { get; set; }
string title;
string artist;
string album;
uint year;
string genre;
public Songs GetSongs()
{
DirectoryInfo di = new DirectoryInfo("C:/Users/USER/MyMusic");
FileInfo[] Files = di.GetFiles("*.mp3"); //Getting mp3 files
foreach (FileInfo file in Files)
{
string fileName = file.FullName;
TagLib.File tagFile = TagLib.File.Create(fileName);
title = tagFile.Tag.Title;
artist = tagFile.Tag.FirstAlbumArtist;
album = tagFile.Tag.Album;
year = tagFile.Tag.Year;
genre = tagFile.Tag.FirstGenre;
//string duration = tagFile.Tag.time;
}
return new Songs { new Song { Name = title, Artist = artist, Album = album, Year = year, Genre = genre } };
}
}
}
歌曲类
using System.Collections.ObjectModel;
namespace MusicPlayer
{
public class Songs : ObservableCollection<Song>
{
}
}
歌曲课程
namespace MusicPlayer
{
public class Song
{
public string Name { get; set; }
public string Artist { get; set; }
public string Album { get; set; }
public string Duration { get; set; }
public uint Year { get; set; }
public string Genre { get; set; }
}
}
xaml.cs文件
using System.Windows;
namespace MusicPlayer
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
MainWindowViewModel mainWindowViewModel;
public MainWindow()
{
InitializeComponent();
mainWindowViewModel = new MainWindowViewModel();
DataContext = mainWindowViewModel;
}
}
}
答案 0 :(得分:0)
从代码片段中看,您只需在列表中添加一首歌曲。如果Songs类真的只是从ObservableCollection派生,你可以删除它并直接使用ObservableCollection。 因此,在foreach循环之前初始化列表,然后在循环中添加歌曲:
DirectoryInfo di = new DirectoryInfo("C:/Users/USER/MyMusic");
FileInfo[] Files = di.GetFiles("*.mp3"); //Getting mp3 files
var songs = new ObservableCollection<Song>();
foreach (FileInfo file in Files)
{
string fileName = file.FullName;
TagLib.File tagFile = TagLib.File.Create(fileName);
title = tagFile.Tag.Title;
artist = tagFile.Tag.FirstAlbumArtist;
album = tagFile.Tag.Album;
year = tagFile.Tag.Year;
genre = tagFile.Tag.FirstGenre;
//string duration = tagFile.Tag.time;
songs.Add(new Song { Name = title, Artist = artist, Album = album, Year = year, Genre = genre });
}
return songs;
您的歌曲属性将改为ObservableCollection类型。此外,你可以跳过公共setter并保持getter使它成为readonly属性(因为我们只在构造函数中设置它很好):
public MainWindowViewModel()
{
Songs = GetSongs();
}
public ObservableCollection<Song> Songs { get; }