WPF DataGrid 虚拟化如何自动生成行号
WPF DataGrid 虚拟化默认不会自动生成行号,需要手动添加。
- 在 DataGrid 中添加一个列,用于显示行号。
<DataGrid.Columns>
<DataGridTextColumn Header="#" IsReadOnly="True"
Binding="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow},
Converter={StaticResource RowToIndexConverter}}" />
<!-- 其他列 -->
</DataGrid.Columns>
- 创建一个行号转换器(RowToIndexConverter),将 DataGridRow 转换为行号。
public class RowToIndexConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DataGridRow row = value as DataGridRow;
if (row != null)
{
return row.GetIndex() + 1;
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
- 在 XAML 中添加行号转换器。
<Window.Resources>
<local:RowToIndexConverter x:Key="RowToIndexConverter" />
</Window.Resources>
现在,DataGrid 就可以自动生成行号了
原文地址: https://www.cveoy.top/t/topic/d46M 著作权归作者所有。请勿转载和采集!