0

我将 EmployeeList 作为 Employee 对象的 observableCollection。

Employee 对象有 Salary。

我想在 XAML 中显示一些值,例如员工的平均薪水,并且当将项目添加到列表中或在任何更新的项目中更改薪水字段时,UI 字段应自动更新。

这可以通过为平均值创建一个属性并侦听列表中的集合 Changed 和 ProperyChanged 处理程序来实现。

但是,我确信应该有其他更好的方法来做到这一点。(如使用 AttachedProperties 或 IValueConverter/IMultiValueConverter)

关于这一点,我有以下问题。

  1. 是否可以将 IMultiValueConverter 用于项目的 List/ObservableCollection?当项目添加到列表以及特定属性更改时应该调用转换器?
4

1 回答 1

1

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.

于 2010-09-29T14:03:35.930 回答