.net DataGrid列中的列/行索引

.net DataGrid列中的列/行索引,.net,wpf,xaml,binding,datagrid,.net,Wpf,Xaml,Binding,Datagrid,我希望以下内容可以在单元格中为我创建列索引: <DataGridTemplateColumn Header="Rec. No." Width="100" IsReadOnly="True"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Text="{Binding Source={RelativeSource Anc

我希望以下内容可以在单元格中为我创建列索引:

<DataGridTemplateColumn Header="Rec. No." Width="100" IsReadOnly="True">
     <DataGridTemplateColumn.CellTemplate>
         <DataTemplate>
              <TextBlock Text="{Binding Source={RelativeSource AncestorType=DataGridCell}, Path=Column.DisplayIndex}" />
         </DataTemplate>
     </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

但事实并非如此。谁能告诉我这里怎么了


我实际上在寻找行索引(在我的网格中需要一个记录编号的列),但是由于
DataGridRow
显然没有“index”类型的属性,我尝试首先为列索引做这件事,它有
DisplayIndex
。但即使这个也不行。

绑定语法不正确。它不应该是
源代码
,而应该是
相对源代码

Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridCell}, 
               Path=Column.DisplayIndex}"

对于获取
RowIndex
的第二个问题,DataGridRow上没有内置属性,例如
RowIndex

我建议在底层数据类中有一些属性并绑定到它。

但是,您也可以通过设置手动获取行索引

public class RowIndexConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, 
                          System.Globalization.CultureInfo culture)
    {
        DependencyObject item = (DependencyObject)value;
        ItemsControl ic = ItemsControl.ItemsControlFromItemContainer(item);

        return ic.ItemContainerGenerator.IndexFromContainer(item);
    }

    public object ConvertBack(object value, Type targetType, object parameter, 
                              System.Globalization.CultureInfo culture)
    {
        return Binding.DoNothing;
    }
}
XAML:

<TextBlock
     Text="{Binding RelativeSource={RelativeSource AncestorType=DataGridRow}, 
                          Converter={StaticResource RowIndexConverter}}"/>


当然,要使用它,您需要在XAML的参考资料部分下声明转换器实例。

谢谢。这解决了一半的问题。现在您看到了获取行索引的方法了吗?DataGridRow上没有内置属性。您可以在基础数据类中具有index属性,也可以在适当的位置使用转换器手动获取行索引。在答案中更新。。!!