Column/Row index in a DataGrid column

.net, binding, datagrid, wpf, xaml

Solution

Binding syntax is incorrect. Instead of `Source`, it should be `RelativeSource`:

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

And for second problem for getting `RowIndex`, there is no inbuilt property such as `RowIndex` on DataGridRow.

I would suggest to have some property in underlying data class and bind to that.

However, you can get rowIndex manually as well by having IValueConverter in place.

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}}"/>

Ofcourse, you need to declare instance of Converter under resources section of your XAML to use that.

Problem

I was hoping the following would get me column index in the cell: ``` <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> ``` But it didn't. Anyone can tell me what's wrong here? I'm actually looking for the row index (need a Record No. column in my grid), but since `DataGridRow` doesn't apparently have an "index" kind of property, I tried to first do it for column index, which has got `DisplayIndex`. But even this one doesn't work.

Original source