DataGrid - Displaying Running Total From Top of Grid Through Current Row
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,
BenEdit: 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).
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.
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
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.
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
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
long cumulative = 0;
List<int> Values = GetValues();
Values.ForEach(v => v.RunningTotal = cumulative = cumulative + v.Value);
You can just run foreach for the whole list and get your running total by the formula
(RunningTotal = cumulative = cumulative + Value);
We need to continously save the previous value.
精彩评论