簡體   English   中英

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當前值,這是一個無操作委托。 相反,您希望它針對引發事件時出現的任何處理程序引發屬性更改事件。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM