void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
// Adding 1 to make the row count start at 1 instead of 0
// as pointed out by daub815
e.Row.Header = (e.Row.GetIndex() + 1).ToString();
}
public class RowToIndexConv : IValueConverter
{
#region IValueConverter Members
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DataGridRow row = value as DataGridRow;
return row.GetIndex() + 1;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
5 回答
一种方法是在
DataGrid
的LoadingRow事件中添加它们 .Update
要使其与WPF Toolkit中的.NET 3.5 DataGrid一起使用,需要进行一些修改 . 索引仍然正确生成,但使用虚拟化时输出失败 . 对
RowHeaderTemplate
的以下修改修复了这个问题Edit 2012-07-05
如果在源列表中添加或删除项目,则数字将不同步,直到滚动列表,因此再次调用
LoadingRow
. 解决这个问题有点复杂,我现在能想到的最好的解决方案是保持上面的LoadingRow
解决方案 .订阅
dataGrid.ItemContainerGenerator.ItemsChanged
在事件处理程序中,在可视树中查找所有子项
DataGridRows
将 Headers 设置为每个
DataGridRow
的索引这是一个执行此操作的附加行为 . 像这样使用它
DisplayRowNumber
Edit: Apparently scrolling changes the index so the binding won't work like that...
一个(看似)干净的模板解决方案:
XAML:
转换器:
如果添加或删除行,则所有这些方法都不起作用 . 在这种情况下,您应该刷新行索引 . 看看这个行为:
@Fredrik Hedblad的回答对我有用 . 谢谢!
我添加了另一个属性来获取“偏移”值,因此DataGrid可以从0或1(或任何设置)开始 .
要使用该行为,(注意'b'是命名空间)
修改后的类:
LoadingRowEvent由此触发: