问题
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:
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.
回答2:
Using LINQ, you can simply do something along the lines of
var averageSalary = yourEmployeeList.Average(employee => employee.Salary);
Same holds true for the Sum.
来源:https://stackoverflow.com/questions/3810188/calculate-sum-average-based-on-list-of-items-in-wpf