C#:订阅从另一个事件触发的事件

C#: Subscribing to event fired from another event

我正在尝试从 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));
        }
    }
}

在这次通话中:

Utils.RaisePropertyChangedWhenCollectionChanged(this, Collection, PropertyChanged, "Collection");

...您正在传递 PropertyChanged 当前 值,这是一个单独的无操作委托。相反,您希望它为引发事件时存在的任何处理程序引发 属性 changed 事件。例如:

Utils.RaisePropertyChangedWhenCollectionChanged
     (this, Collection, 
      (sender, args) => PropertyChanged(sender, args),
      "Collection");