Column / row index in DataGrid column

I was hoping the following would get me the 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 this is not so. Can anyone tell me what's wrong here?

I am really looking for a row index (I need a column no. Record in my grid), but since it DataGridRowapparently does not have a property of type “index”, I first tried to do this for the index column that I got DisplayIndex. But even this one does not work.

+3
source share
1 answer

The binding syntax is invalid . Instead Sourceit should be RelativeSource:

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

And for the second problem when receiving, RowIndexthere is no built-in property, such as RowIndexin a DataGridRow.

.

rowIndex , IValueConverter.

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, .

+3

All Articles