数据模型和数据模型创建的数据集代码和上一篇代码一样。
只是UI创建的绑定方式不一样,不再默认绑定方式。
效果如下:
1. 依据后台数据类型创建DataContent
<Window.DataContext>
<local:Songs/>
</Window.DataContext>
2. 创建枚举类型的资源
<Window.Resources>
<ObjectDataProvider x:Key="objDataProvider" ObjectType="{x:Type GenreEnum:Enum}" MethodName="GetNames" >
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Genre"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
3.创建绑定
<Grid>
<DataGrid FontSize="14" ItemsSource="{Binding songList}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="ID"
Binding="{Binding Id}"></DataGridTextColumn>
<DataGridTextColumn Header="SONG TITLE" Binding="{Binding Title}"/>
<DataGridTextColumn Header="ARTIST"
Binding="{Binding Artist}"></DataGridTextColumn>
<DataGridCheckBoxColumn Header="SOUNDTRACK"
Binding="{Binding IsSoundtrack}"></DataGridCheckBoxColumn>
<DataGridTextColumn Header="MOVIE TITLE"
Binding="{Binding MovieTitle}"></DataGridTextColumn>
<DataGridComboBoxColumn Header="GENRE" TextBinding="{Binding Genre}"
ItemsSource="{Binding Source={StaticResource objDataProvider}}"/>
<DataGridTextColumn Header="YEAR"
Binding="{Binding ReleaseDateTime,StringFormat=yyyy}"></DataGridTextColumn>
<DataGridHyperlinkColumn Header="URL" Binding="{Binding URL}"></DataGridHyperlinkColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
4.后台数据类型
public class Song
{
public int Id { get; set; }
public string Title { get; set; }
public string Artist { get; set; }
public bool IsSoundtrack { get; set; }
public string MovieTitle { get; set; }
public Genre Genre { get; set; }
public DateTime ReleaseDateTime { get; set; }
public Uri URL { get; set; }
}
public enum Genre
{
HeavyMetal, HardRock, SoftRock, ClassicRock, Rock, Pop, PopSoul, Soul, Blues, Jazz, RB, Country, Folk, Funk,
Classical, ChristmasCarol, Classic
}
5. 创建数据集
public class Songs
{
public List<Song> songList { get; set; } = GetSongs();
public static List<Song> GetSongs()
{
var file = System.IO.Path.Combine($"{ AppDomain.CurrentDomain.BaseDirectory}", "songs.txt");
//@"C:\Users\Ritchie.li\Desktop\WPF DataGrid\WpfApp\bin\Debug\songs.txt";
var lines = File.ReadAllLines(file);
var list = new List<Song>();
for (int i = 0; i < lines.Length; i++)
{
try
{
var line = lines[i].Split(',');
var temp = line[2].Split(' ', '&', '-');
var gr = temp.Length > 1 ? temp[0] + temp[1] : temp[0];
var song = new Song()
{
Id = int.Parse(line[0]),
Title = line[1],
Artist = line[3],
IsSoundtrack = line[4].Trim() == "Unknown" ? false : true,
MovieTitle = line[4],
Genre = (Genre)Enum.Parse(typeof(Genre), gr),
URL = new Uri($"www.{line[3]}.com", UriKind.Relative),
ReleaseDateTime = DateTime.Parse(line[5] + ",01,01")
};
list.Add(song);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
return list;
}
}
网友评论