Subscribe to INotifyPropertyChanged for nested (child) objects

后端 未结 6 1271
执念已碎
执念已碎 2020-12-04 22:05

I\'m looking for a clean and elegant solution to handle the INotifyPropertyChanged event of nested (child) objects. Example code:

<         


        
6条回答
  •  时光说笑
    2020-12-04 22:45

    I wrote an easy helper to do this. You just call BubblePropertyChanged(x => x.BestFriend) in your parent view model. n.b. there is an assumption you have a method called NotifyPropertyChagned in your parent, but you can adapt that.

            /// 
        /// Bubbles up property changed events from a child viewmodel that implements {INotifyPropertyChanged} to the parent keeping
        /// the naming hierarchy in place.
        /// This is useful for nested view models. 
        /// 
        /// Child property that is a viewmodel implementing INotifyPropertyChanged.
        /// 
        public IDisposable BubblePropertyChanged(Expression> property)
        {
            // This step is relatively expensive but only called once during setup.
            MemberExpression body = (MemberExpression)property.Body;
            var prefix = body.Member.Name + ".";
    
            INotifyPropertyChanged child = property.Compile().Invoke();
    
            PropertyChangedEventHandler handler = (sender, e) =>
            {
                this.NotifyPropertyChanged(prefix + e.PropertyName);
            };
    
            child.PropertyChanged += handler;
    
            return Disposable.Create(() => { child.PropertyChanged -= handler; });
        }
    

提交回复
热议问题