我会做这样的事情(假设一个名为 observable 的 ObservableCollection 和使用 RaisePropertyChanged 方法实现 INotifyPropertyChanged 的类):
public IEnumerable<string> NewList
{
return from item in observable
select item.Name;
}
observable.CollectionChanged += delegate { RaisePropertyChanged("NewList"); };
然后,当 observable 更改时,UI 将被告知 NewList 已更改并重新评估查询。
对于多个从属项目,您可以执行以下操作:
observable.CollectionChanged += delegate
{
RaisePropertyChanged("NewList",
"OtherProperty",
"YetAnotherProperty",
"Etc");
};
Update
上面的方法通常对于属性来说效果很好,因为每次访问它时您都会获得最新的值,并且 INPC 可用于告诉事物重新读取它。
对于稍微更有趣的集合案例,我将实现一个自定义类,该类实现 INotifyCollectionChanged 和 IEnumerable 并包装 LINQ。例如。,
public class CustomObservableCollection<T> : INotifyCollectionChanged,
INotifyPropertyChanged,
IEnumerable<T>
{
private readonly IEnumerable<T> _collection;
public CustomObservableCollection(IEnumerable<T> collection)
{
_collection = collection;
}
public IEnumerator<T> GetEnumerator()
{
_collection.GetEnumerator();
}
public void RaiseCollectionChanged() { ... }
...
}
然后你可以这样做:
var newList = new CustomObservableCollection(from item in observable
select item.Name);
observable.CollectionChanged += delegate { newList.RaiseCollectionChanged(); };
Update 2
您甚至可以将依赖项传递给 Custom ObservableCollection:
public class CustomObservableCollection<T> : INotifyCollectionChanged,
INotifyPropertyChanged,
IEnumerable<T>
{
private readonly IEnumerable<T> _collection;
public CustomObservableCollection(IEnumerable<T> collection,
params ObservableCollection[] dependencies)
{
_collection = collection;
foreach (var dep in dependencies)
dep.CollectionChanged += RaiseCollectionChanged();
}
public IEnumerator<T> GetEnumerator()
{
_collection.GetEnumerator();
}
public void RaiseCollectionChanged() { ... }
...
}