How to capture a property changed even of one view model in another view model

StackOverflow https://stackoverflow.com/questions/18635463

  •  27-06-2022
  •  | 
  •  

Pergunta

i have view model class A and it has the property "a".

and i have class called B , and it ha sproperty "b" where i store list of all A[] as list.

if any change in the property a , i would like to change the property in the parent class A.

that is

class B {

property b1;

List A[]

}

Class A {

property a1;

}

I am using MVVM and notify property chnaged event is there in both the places. what i dont know how to wire up both .

Foi útil?

Solução

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;

Outras dicas

Create View Model A as Singleton and update the a property using that instance.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top