You can use ReactiveUI's reactive collection, which provides a number of observables including one for when the collection changes (Changed
), and one for when the items in the collection change (ItemChanged
). This can be combined with ObservableAsPropertyHelper
for the dependent properties.
The totalOfAll
dependent property is quite straightforward. The other dependent property - groupedObjects
- is a bit more complex. I'm not sure if I've understood your grouping requirements exactly. Hopefully the code below will be a starting point - it will project the collection of subobjects into an IEnumerable
of anonymous objects, each containing a total, a row header, and the items. You should be able to bind to this in your view
public class MyObject : ReactiveObject
{
public ReactiveCollection<MySubObject> Objects { get; set; }
private ObservableAsPropertyHelper<IEnumerable<object>> groupedObjectsHelper;
public IEnumerable<object> GroupedObjects
{
get {return groupedObjectsHelper.Value;}
}
private ObservableAsPropertyHelper<Decimal> totalOfAllHelper;
public Decimal TotalOfAll
{
get {return totalOfAllHelper.Value;}
}
public MyObject()
{
var whenObjectsChange=
Observable.Merge(Objects.Changed.Select(_ => Unit.Default),
Objects.ItemChanged.Select(_ => Unit.Default));
totalOfAllHelper=
whenObjectsChange.Select(_=>Objects.Sum(o => o.Value))
.ToProperty(this, t => t.TotalOfAll);
groupedObjectsHelper=
whenObjectsChange.Select(_=>Objects
.GroupBy(o => o.RowType)
.Select(g => new {RowType=g.Key,
RowTotal=g.Sum(o => o.Value),
Objects=g}))
.ToProperty(this, t => t.GroupedObjects);
}
}