views:

27

answers:

1

I have EmployeeList as a observableCollection of Employee Object.

The Employee object has Salary.

I want to display few values like average Salary of the Employees in XAML, and the UI field should be automatically updated when an item is added to the List or When Salary field is changed in any of the items updated.

This can be achieved by creating a property for average and listening to collection Changed and ProperyChanged handlers in the list.

But, I am sure that there should be some other better way to do this. (Like using AttachedProperties or IValueConverter/IMultiValueConverter)

Regarding This, I have following questions.

  1. Is It possible to use IMultiValueConverter for a List/ObservableCollection of Items? The converter should be called when an Item Added to the list as well as when a particular property changed?
+1  A: 

Using a property is definitely the way to go, especially from an MVVM standpoint. Think Occam's Razor: basically, the simplest solution is usually the best.

It's certainly the cleanest solution, and thus most maintainable. Plus, it is the most expandable (you can easily add new properties for different calculations if you'd like).

All you need to do is create read-only properties, and call PropertyChanged with that property's name when the collection changes (which it sounds like you are doing).

For example, here's an "Average" property:

public Double Average   
{
    get { return mMyCollection.Average(); }
}

void mMyCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    PropertyChanged(this, new PropertyChangedEventArgs("Average"));
}

Attached properties won't work - they are for specifying a parent's property in a child element.

ValueConverters would work, in theory (although they would probably have to be on each item in the list, as well as the entire collection), but you're not really converting anything, you are providing additional data based on existing data. To do that, you would need to muck around with all kinds of Templates, and any time you needed to change anything, you'll need to muck around with them again. It would get complex in a hurry, and for no benefit.

Wonko the Sane