I am looking to get the row number into the RowHeader of the WPF 4 DataGrid so it has an Excel-like column for the row numbers of the DataGrid.
The solution I've seen out there on the web suggests adding an index field to the business objects. This isn't really an option because the DataGrid will be getting resorted a lot and we don't want to have to keep track of changing these index fields constantly.
Thanks a lot
One way is to add them in the LoadingRow event for the
DataGrid
.Update
To get this to work with the .NET 3.5 DataGrid in WPF Toolkit a little modification is needed. The index is still generated correctly but the output fails when using virtualization. The following modification to the
RowHeaderTemplate
fixes thisEdit 2012-07-05
If items are added or removed from the source list then the numbers get out of sync until the list is scrolled so
LoadingRow
is called again. Working around this issue is a little more complex and the best solution I can think of right now is to keep theLoadingRow
solution above and alsodataGrid.ItemContainerGenerator.ItemsChanged
DataGridRows
in the visual treeDataGridRow
Here is an attached behavior which does this. Use it like this
DisplayRowNumber
All of this approaches will not work if you add or remove rows. You should refresh row indexes in such cases. Look at this behavior:
Edit: Apparently scrolling changes the index so the binding won't work like that...
A (seemingly) clean templating solution:
Xaml:
Converter:
LoadingRowEvent is triggered by this:
@Fredrik Hedblad's answer works for me. Thanks!
I added another property to get an "offset" value so the DataGrid can start from either 0 or 1 (or whatever is set).
To use the behavior, (note 'b' is the namespace)
The modified classes: