我正在尝试从 CollectionChanged 回调中引发 PropertyChangedEventHandler。它被提升了,但它没有到达订阅者。
也许我不能把 EventHandler 当作一个变量来对待?尽管我过去这样做没有问题,但它只是从另一个我遇到问题的事件中提出来的。
任何帮助表示赞赏,谢谢。
using System;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;
namespace Fire
{
/// <summary>
/// Simple class implementing INotifyPropertyChanged
/// I want to raise PropertyChanged whenever the ObservableCollection changes.
/// </summary>
public class Model : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
public ObservableCollection<int> Collection { get; set; }
public Model()
{
Collection = new ObservableCollection<int>();
// In theory it should be sorted out here:
Utils.RaisePropertyChangedWhenCollectionChanged(this, Collection, PropertyChanged, "Collection");
}
}
/// <summary>
/// I want to wrap the "If CollectionChanged then raise PropertyChanged" logic in a utility method".
/// </summary>
public class Utils
{
public static void RaisePropertyChangedWhenCollectionChanged(object owner, INotifyCollectionChanged collection, PropertyChangedEventHandler eventHandler, string propertyName)
{
collection.CollectionChanged += (object sender, NotifyCollectionChangedEventArgs e) =>
{
eventHandler(owner, new PropertyChangedEventArgs(propertyName));
};
}
}
class Program
{
static void Main(string[] args)
{
Model model = new Model();
model.PropertyChanged += model_PropertyChanged;
// But the problem is that PropertyChanged does not fire, even when the collection is changed.
model.Collection.Add(2);
}
static void model_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// This does not get called!
Console.Out.WriteLine(String.Format("{0}", e.PropertyName));
}
}
}