前台xaml:
响应LoadingRow事件,绑定了DataGridRow.Header属性,然后为Header属性赋值。RowHeaderWidth = 0是把默认的行表头隐藏掉,用自己绑定的列。
<DataGrid Grid.Row="1" ItemsSource="{Binding WeaponStateNumModels}" Margin="2" RowHeaderWidth="0" LoadingRow="DataGrid_LoadingRow">
<DataGrid.Columns>
<DataGridTextColumn Header="序号" Width="80" Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type DataGridRow}},Path=Header}"/>
<DataGridTextColumn Header="名称" Width="*"/>
<DataGridTextColumn Header="类型" Width="*" />
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
后台代码:
private void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = e.Row.GetIndex() + 1;
}