Question

I just want to add a index column in wpf toolkit DataGrid to show row index of each data in the DataGrid. How?

<dg:DataGrid ItemsSource="{Binding List}"                              
             SelectionMode="Extended"
             IsReadOnly="True"
             AutoGenerateColumns="False"
             HorizontalAlignment="Left">
    <dg:DataGrid.Columns>

        **<dg:DataGridTextColumn Header="Row Index"></dg:DataGridTextColumn>**
        <dg:DataGridTextColumn Header="Branch"
                               Binding="{Binding Branch.Id}"></dg:DataGridTextColumn>
        <dg:DataGridTextColumn Header="Count"
                               Binding="{Binding RequestCount}"></dg:DataGridTextColumn>
    </dg:DataGrid.Columns>
</dg:DataGrid>
Was it helpful?

Solution

you can use a multibinding and a converter to bind to the item in the row and the parent datagrid. then in the converter you look up the position of the row in the datagrids items.

On this page download the sample WPFDatagridWithRowNumbers.zip

Enjoy!

OTHER TIPS

I don't have a code sample right now, but accoring to this post there is "a LoadingRow event that you can attach to. In the event you can set the header each time to the number you want based on the item in the event args."

That is the only way I could find to do it. There does not seem to be an elegant XAML solution.

Forget multibinding and converters. You can do this entirely in XAML.

First, bind the AlternationCount property of your data grid to either the the count property of your collection, or to the Items.Count property of your DataGrid as follows:

<dg:DataGrid AlternationCount="{Binding List.Count}" />

Or:

<dg:DataGrid AlternationCount="{Binding Items.Count, RelativeSource={RelativeSource Self}" />

Either should work.

Then, assuming you're using a DataGridTextColumn for your leftmost column you do the following in your DataGrid.Columns definition:

<dg:DataGrid.Columns>
   <dg:DataGridTextColumn Binding="{Binding AlternationIndex, RelativeSource={RelativeSource AncestorType=DataGridRow}}"
</dg:DataGrid.Columns>

If you don't want to start at 0, you can add a converter to your alternation index binding to increment the index.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top