1、DataGrid创建
<DataGrid x:name="表格" itemsource="必须绑定">
</DataGrid>
2、列属性
设置列宽填充表格
<DataGridTextColumn Header="焊接面" Width="*" Binding="{Binding surface}"/>
3、数据源绑定
后台代码
//引入命名空间
using System.Collections.ObjectModel;
ObservableCollection<Student> list = new ObservableCollection<Student>();
this.datagrid.source=list;
public Struct Student{
public String Name{set;get;}
public int Age{set;get;}
}
前台代码
<DataGrid itemsource={bingding} AutoGenerateColumns="false" >
...........
...........
...........
</DataGrid>
4、绑定数据并不追加列
AutoGenerateColumns
False:不自动增加列
True:自动增加列
5、列排序
CanUserSortColumns
False:不可以排序
True:可以排序
6、允许用户追加行
CanUserAddRows
True:可以增加
False:不可以增加
7、允许用户调整列宽
CanUserResizeColumns
8、获取单元格中的值
(DG_Surface.Columns[0].GetCellContent(DG_Surface.Items[1]) as TextBlock).Text.ToString()
注意:好像更改内容后不可以刷新
9、数据源绑定
使用mvvm模式下数据绑定就是控件属性的绑定。可以双向更新
使用单独的属性进行绑定,可以封装并不需要继承observe
绑定数据后会多一行空白行可以使用指令CanUserAddRows="False"取消空白行
10、实时刷新展示数据的最后一行
var border= VisualTreeHelper.GetChild(this.datagrid, 0) as Decorator;
if (border != null)
{
var scroll = border.Child as ScrollViewer;
if (scroll != null) scroll.ScrollToEnd();
}
<Button
Style="{StaticResource bt}"
Content="下载"
Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}},Path=DataContext.IDownlad}"/>
11、设置datagrid样式信息
1、列头居中显示
2、设置DataGridColumnText的样式使用ElementStyle进行绑定样式即可修改文字的样式,并修改TargetType='TextBlock'
3、 设置DataGridColumnText的单元格样式使用CellStyle进行绑定样式即可修改背景等,修改TargetType='DataGridCell'
//表头样式
<Style TargetType="DataGridColumnHeader">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
</Style>
//背景样式
<Style TargetType="DataGridCell" x:Key="cell">
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Red"/>
</Style>
//文字样式
<Style TargetType="TextBlock" x:Key="dgcell">
<Setter Property="HorizontalAlignment" Value="Center"/>
<Setter Property="VerticalAlignment" Value="Center"/>
</Style>
<DataGridTextColumn Header="物料编码" CellStyle="{StaticResource cell}" ElementStyle="{StaticResource dgcell}" Binding="{Binding Material_Code }" Width="20*" >
</DataGridTextColumn>
3、选中单个cell
SelectionMode="Single";设置不能多选
SelectionUnit="Cell" 设置只能选中单个元素