WPF中DataGrid前面加上序号
首先在XAML页面中的DataGrid中添加一列
<DataGridTemplateColumn Header=" 序号" HeaderStyle="{StaticResource DataGridColumnHeaderStyle1}" Width="50" MinWidth="10" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="10,0,0,0"></TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
然后在DataGrid上添加一个LoadingRow事件,该事件的处理方法如下
private void dataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = e.Row.GetIndex() + 1;
}