代码之家  ›  专栏  ›  技术社区  ›  user3299166

另一类属性中的可观察集合

  •  1
  • user3299166  · 技术社区  · 10 年前

    假设我有一个实现 INotifyPropertyChanged ,其中财产之一是其成员为 ObservableCollections :

    namespace Example
    {
        public class A : INotifyPropertyChanged
        {
            private B _prop;
            public B Prop 
            {
                get { return _prop; }
                set 
                {
                    _prop = value;
                    NotifyPropertyChanged("Prop");
                }
            }
    
            public A() { Prop = new B(); }
    
            //"Some Property" related Prop.words
    
        }
    
        public class B 
        {
            public ObservableCollection<String> words { get; set; }
    
            public B() { words = new ObservableCollection<String>(); }
        }
    
    }
    

    我对如何在课堂上通知该属性感到困惑 A 什么时候 Prop.words 变化。在哪个类中实现处理程序 INotifyCollectionChanged ?

    编辑:我之前没有指定上下文,但我在“Some Property”上绑定了一个WPF控件,当 道具词 变化。

    2 回复  |  直到 10 年前
        1
  •  2
  •   Rohit Vats    10 年前

    如果需要通知A类,那么您必须 类A中的hook CollectionChanged 只有在Prop。

    确保在属性B设置为新值的情况下解除处理程序的连接,以避免任何内存泄漏。

    public class A : INotifyPropertyChanged
    {
        private B _prop;
        public B Prop
        {
            get { return _prop; }
            set
            {
                if(_prop != null)
                    _prop.words.CollectionChanged -= words_CollectionChanged;
                _prop = value;
                if (_prop != null)
                    _prop.words.CollectionChanged += words_CollectionChanged;
                NotifyPropertyChanged("Prop");
            }
        }
    
        void words_CollectionChanged(object sender, 
                                     NotifyCollectionChangedEventArgs e)
        {
            // Notify other properties here.
        }
    
        public A() { Prop = new B(); }
    
        //Some Property related Prop.words
    
    }
    
        2
  •  0
  •   Pragmateek    10 年前

    的客户 A 类应该处理这个问题。

    IMHO提升 PropertyChanged 当基础集合发生更改时 功能性合同 属于 INotifyPropertyChanged .

    此外,假设您有一个绑定到集合的项控件:每次集合更改时,它都会完全反弹,因为我们通知它已经完全更改,绝对不是您想要的!

    A a = new A();
    ...
    a.Prop.Words.CollectionChanged += ...
    

    如果绑定到 Prop 财产。

    请注意,从教条的OO设计角度来看,这违反了Demeter定律,因此您可以将Words集合放在a类型中以避免出现这种情况,但这是另一个问题/争论。