In my BaseCollection
class which extends ObservableCollection<T>
, I have a created a CollectionItemPropertyChanged
delegate
that I can attach a handler to, so I can be notified when property values have changed in any item in the collection:
public delegate void ItemPropertyChanged(T item, string propertyName);
Then I add a getter and setter of the type of the delegate
:
public virtual ItemPropertyChanged CurrentItemPropertyChanged { get; set; }
To achieve this, I have to attach a handler to each item's PropertyChanged
event:
public BaseCollection(IEnumerable<T> collection)
{
foreach (T item in collection) Add(item);
}
public new void Add(T item)
{
item.PropertyChanged += Item_PropertyChanged;
base.Add(item);
}
I also need to remove the handlers when objects are removed:
public new bool Remove(T item)
{
if (item == null) return false;
item.PropertyChanged -= Item_PropertyChanged;
return base.Remove(item);
}
Then there is the Item_PropertyChanged
handler:
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (CollectionItemPropertyChanged != null) CollectionItemPropertyChanged(
currentItem, e.PropertyName);
}
This can then be used in your class B
like so:
public List<A> Items
{
get { return items; }
set
{
items = value;
items.CollectionItemPropertyChanged += YourHandler;
NotifyPropertyChanged(Items);
}
}
Then your handler:
private void YourHandler(A item, string propertyName)
{
// propertyName is the name of the changed property from the A object named item
}
To answer your question more directly, you can attach a handler from one view model to this delegate
in another... for example:
Items.CollectionItemPropertyChanged += ViewModel2.YourHandler;
Or from the other view model:
ViewModel1.Items.CollectionItemPropertyChanged += YourHandler;