DataGrid控件所使用的数据源也是一个集合类。通常使用ObservableCollection泛型类。而不使用List泛型类。因为ObservableCollection类内部自带通知功能。
使用DataGrid控件绑定的时候,通常可以构建一个类,代码如下:
public class GridData
{
public string Name { get; set; }
public int Age { get; set; }
public bool Male { get; set; }
public static ObservableCollection<GridData> GetData()
{
ObservableCollection<GridData> data = new ObservableCollection<GridData>();
data.Add(new GridData()
{
Name = "John Doe",
Age = 30,
Male = true
});
data.Add(new GridData()
{
Name = "Jane Doe",
Age = 32,
Male = false
});
data.Add(new GridData()
{
Name = "Jason Smith",
Age = 54,
Male = true
});
data.Add(new GridData()
{
Name = "Kayli Jayne",
Age = 25,
Male = false
});
return data;
}
}
绑定语句:
this.dataGrid1.ItemsSource = GridData.GetData();
对于dataGrid,有两种方式生成列,一直是自动生成,一种是手动生成。代码如下:
<sdk:DataGrid AutoGenerateColumns="True" Height="140" HorizontalAlignment="Left" Margin="34,27,0,0" Name="dataGrid1" VerticalAlignment="Top" ;247" />
<sdk:DataGrid AutoGenerateColumns="False" Height="140" HorizontalAlignment="Left" Margin="34,247,0,0" Name="dataGrid2" VerticalAlignment="Top" ;247">
<sdk:DataGrid.Columns>
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" ;Auto" Binding="{Binding Name}" Foreground="#FFE27474" Header="Name" IsReadOnly="True" />
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" ;Auto" Binding="{Binding Age}" Header="Age" IsReadOnly="True" />
<sdk:DataGridTextColumn CanUserReorder="True" CanUserResize="True" CanUserSort="True" ;Auto" Binding="{Binding Male}" Header="Male" IsReadOnly="True" />
</sdk:DataGrid.Columns>
</sdk:DataGrid>
更多细节:http://msdn.microsoft.com/zh-cn/library/system.windows.controls.datagrid%28VS.95%29.aspx