您好我尝试了几种方法,但要么不成功,要么不理想。我只是想 捕获集合中任何项的PropertyChanged事件。我现在手动连接了它 但我想知道是否有更优雅的解决方案:
public class Item : INotifyPropertyChanged
{
...
public delegate void MyPropertyChangedHandler(object sender, PropertyChangedEventArgs e);
public event MyPropertyChangedHandler MyPropertyChanged;
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventArgs args = new PropertyChangedEventArgs(propertyName);
PropertyChanged(this, args);
if (MyPropertyChanged != null) MyPropertyChanged(this, args);
}
...
}
public class ItemCollection : ObservableCollection<Item>
{
...
public delegate void MyPropertyChangedHandler(object sender, PropertyChangedEventArgs e);
public event MyPropertyChangedHandler MyPropertyChanged;
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (Item item in e.NewItems)
{
item.MyPropertyChanged += new Item.MyPropertyChangedHandler(item_MyPropertyChanged);
}
}
base.OnCollectionChanged(e);
}
void item_MyPropertyChanged(object sender, PropertyChangedEventArgs e)
{
MyPropertyChanged(sender, e);
}
...
}
然后我可以很容易地附加到该系列的MyPropertyChanged事件中,它运行良好,但更优雅的任何人?
提前致谢
答案 0 :(得分:3)
你几乎正在做你需要做的事情,AFIK没有更好的方法来做到这一点。
有一件事,您可能希望添加代码以在从集合中删除项目时删除事件处理程序,成为一个好公民并避免内存泄漏。