先展示一下样式效果,如下:
UI XAML代码如下:
<Window x:Class=“wpf_DataGird_Test.MainWindow”
xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:d=“http://schemas.microsoft.com/expression/blend/2008”
xmlns:mc=“http://schemas.openxmlformats.org/markup-compatibility/2006”
xmlns:local=“clr-namespace:wpf_DataGird_Test”
mc:Ignorable=“d”
Title=“DataGrid Demo1” Height=“450” Width=“800”>
<DataGrid x:Name=“dg” Margin=“5”
AutoGenerateColumns=“False”
LoadingRow=“dg_LoadingRow”
CanUserAddRows=“False”
RowHeaderWidth=“20”>
<DataGrid.ColumnHeaderStyle>
</DataGrid.ColumnHeaderStyle>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Name}" IsReadOnly=“True” Header=“Author Name”
Width=“160” FontFamily=“Georgia” FontSize=“18” FontWeight=“Black” SortDirection=“Descending”/>
</DataGrid.Columns>
在后台代码中添加数据模型:
public class Author
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime DOB { get; set; }
public string BookTitle { get; set; }
public bool IsMVP { get; set; }
public string Email { get; set; }
public string City { get; set; }
public string Country { get; set; }
public int Zip { get; set; }
}
窗口页面的后台代码:
namespace wpf_DataGird_Test
{
///
/// MainWindow.xaml 的交互逻辑
///
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
dg.ItemsSource = CreateDemoSource();
}
//
private void dg_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
//创建数据源
private List CreateDemoSource()
{
List authors = new List();
authors.Add(new Author()
{
ID = 101,
Name = “Mahesh Chand”,
BookTitle = “Graphics Programming with GDI+”,
DOB = new DateTime(1975, 2, 23),
IsMVP = false
});
authors.Add(new Author()
{
ID = 201,
Name = “Mike Gold”,
BookTitle = “Programming C#”,
DOB = new DateTime(1982, 4, 12),
IsMVP = true
});
authors.Add(new Author()
{
ID = 244,
Name = “Mathew Cochran”,
BookTitle = “LINQ in Vista”,
DOB = new DateTime(1985, 9, 11),
IsMVP = true
});
return authors;
}
}
}