DataGrid 经常用作数据的展示,例如:
1. UI设计
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<!--Row0-->
<TextBlock Grid.Row="0" HorizontalAlignment="Center" Foreground="Green" FontStyle="Italic" FontSize="25">
Using DataGrid Control Show Data
</TextBlock>
<DataGrid Grid.Row="1" Margin="5" AutoGenerateColumns="False" x:Name="simpleDemoDataGrid"
HorizontalGridLinesBrush="LightGreen" CanUserAddRows="False" IsReadOnly="True"
VerticalGridLinesBrush="Black">
<DataGrid.Columns>
<DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="50"/>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" Width="100"/>
<DataGridTextColumn Header="PhoneNumber" Binding="{Binding PhoneNumber}" Width="120"/>
<DataGridTextColumn Header="Address" Binding="{Binding Address}" Width="200"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
2. 后台代码
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.simpleDemoDataGrid.ItemsSource = CreteDemoData().DefaultView;
this.simpleDemoDataGrid.GridLinesVisibility = DataGridGridLinesVisibility.All;
}
static DataTable CreteDemoData()
{
DataTable dt = new System.Data.DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("PhoneNumber", typeof(string));
dt.Columns.Add("Address", typeof(string));
DataRow row = dt.NewRow();
row["ID"] = 1;
row["Name"] = "Jack";
row["PhoneNumber"] = "123456";
row["Address"] = "Beijin";
dt.Rows.Add(row);
row = dt.NewRow();
row["ID"] = 2;
row["Name"] = "Tom";
row["PhoneNumber"] = "789001";
row["Address"] = "Shanghai";
dt.Rows.Add(row);
row = dt.NewRow();
row["ID"] = 3;
row["Name"] = "Jerry";
row["PhoneNumber"] = "67767";
row["Address"] = "Shenzhen";
dt.Rows.Add(row);
return dt;
}
}
创建一个DataTable 数据源,在窗口初始化时绑定。DataTable的原始数据可以来自数据库,文件等。