0

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

1 回答 1

1

在本次通话中:

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

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

Utils.RaisePropertyChangedWhenCollectionChanged
     (this, Collection, 
      (sender, args) => PropertyChanged(sender, args),
      "Collection");
于 2015-07-15T16:09:29.180 回答