How to show row index for wpf toolkit datagrid?

女生的网名这么多〃 提交于 2019-11-30 18:04:17

问题


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>

回答1:


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!




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/2041168/how-to-show-row-index-for-wpf-toolkit-datagrid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!