views:

26

answers:

2

Hi,

In WPF, I want to display sum, average values based on the List of Items provided.

For example, I have an Employee object with Salary Property, and I want to calculate total salary based on the employee list. Also, the employee object is data bound to a Items control where the Salary will be edited/new Employee may be added to the list.

Can anyone provide me a solution to achieve this?

+1  A: 

Using LINQ, you can simply do something along the lines of

var averageSalary = yourEmployeeList.Average(employee => employee.Salary);

Same holds true for the Sum.

Jim Brissom
I want to do it in the binding and it should listen to the changes in the salary as well as the items in teh list.
Elangovan
+1  A: 

I would do this:

In your code behind or ViewModel (if your using MVVM) create a new dependency property called AverageSalary.

Then change Salary on the employee to also be a dependency property. In the code behind you can then listen to when the Employee.Salary changes. (see this link for details on that) And when it changes recompute the average like listed above then assign it to the AverageSalary dependency property you created.

Then just bind your UI to the AverageSalary property and it should update as the employee's salaries change.

Kelly
This is one way of doing this, but I wat to avoid event listeners in XAML, instead i am trying to achieve this XAML, using attached properties, or IMultivalueConverter.
Elangovan