我使用了安迪的示例,但是我需要从代码后端使用它,所以这是我的代码,以防有人想要做同样的事情,因为谷歌搜索结果很少。
C# 代码:
DataGrid dataGrid = new DataGrid();
DataGridTextColumn column0 = new DataGridTextColumn();
column0.Header = "#";
Binding bindingColumn0 = new Binding();
bindingColumn0.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(DataGridRow), 1);
bindingColumn0.Converter = new RowToIndexConvertor();
column0.Binding = bindingColumn0;
dataGrid.Columns.Add(column0);
Andy的转换器,刚刚添加了return row.GetIndex() - 1;
以从1开始计数,而不是0。
(此内容涉及IT技术,旨在将计数器从0更改为1)
public class RowToIndexConvertor : MarkupExtension, IValueConverter
{
static RowToIndexConvertor convertor;
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
DataGridRow row = value as DataGridRow;
if (row != null)
{
return row.GetIndex() + 1;
}
else
{
return -1;
}
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
if (convertor == null)
{
convertor = new RowToIndexConvertor();
}
return convertor;
}
public RowToIndexConvertor()
{
}
}
不要忘记使用方式
using System;
using System.Windows.Data;
using System.Windows.Controls;
using System.Windows.Markup;