views:

59

answers:

5

Hello,

How would I display a running total for a particular column of each record that is displayed in a DataGrid? I'd like to keep the computation logic in the view model.

Desired Output:

Value      | Running Total
25           25
10           35
-2           33

Thank you,
Ben

Edit: Keep in mind that when a user-triggered DataGrid sort occurs, the running totals must be recalculated because the record display order has changed.

I'd really like to put the logic for this in the view model, not in WPF code (e.g. not using an IValueConverter).

A: 

I don't know there is a recommended / supported / simple way to do this. The choices I can think of are:
1) Have some ui element outside of the data grid to hold the total. This is easy to bind to your VM but a bit of a pain to work out the alignment issues that will come up, as you likely want the total right under the column. This is what I would recommend.
2) Have a dummy last row in the grid; this solves the alignment problem but adds hacky logic to the VM, and probably doesn't look so great on top of it.

HTH,
Berryl

Berryl
A: 

If you don't mind the answer in VB or C# then this tutorial shows how to do what you want in VB and this tutorial shows it in C#. Both use a dummy column in the grid.

Kyra
@Kyra - yeah, I agree. I was thinking he wanted one total for a column to go underneath it. Cheers
Berryl
A: 

Check out this answer for how to add a row count column to a ListBox and populate using a value converter. Instead of counting item, add up the sum of items. If you need the total sum in your VM this is of course not a good solution.

Numbered listbox

Wallstreet Programmer
Did you have the link for the answer you mentioned?
Ben Gribaudo
Thanks, added the missing link
Wallstreet Programmer
This is an interesting approach. Thanks for sharing it. One of the neat things about it is that the objects in the collection passed to the grid's ItemsSource need not have a Balance property.
Ben Gribaudo
A: 

It is only idea: actually, DataGrid uses ICollectionView interface ( http://msdn.microsoft.com/en-us/library/system.componentmodel.icollectionview.aspx) to implement sorting (as described in http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid(VS.95).aspx at Grouping, Sorting, and Filtering section.

So, you can create class that implements ICollectionView interface, and observe sorting with corresponding updating of running total.

STO
A: 

I ended up solving this problem by extending DataGrid to expose a property which could be bound to a "resort has occured" callback on the view model.

Details: http://bengribaudo.com/blog/2010/07/14/3/datagrid-per-row-running-totals

Ben Gribaudo