Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I'm creating 2 instances of the same model for 2 windows. The class to make the communication is named 'manager'.
I want to notify the second window when a property is changed in the first window. The model implements
INotifyPropertyChanged


When the value is changed in the second, it's raising the event
public bool MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        OnPropertyChanged();
    }
}

public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName]string caller = null)
        {
            var handler = PropertyChanged;
            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(caller));
            }
        }



In the manager, I'll receiving a notification and I'm updating all instances of the models
private void Vm_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    var prop = TypeDescriptor.GetProperties(sender)[e.PropertyName];
    if (prop != null)
    {
        object val = prop.GetValue(sender);
        SynchronizeViews(e.PropertyName, val);
    }
}

private void SynchronizeViews(string propertyName, object val)
{
    foreach(MainViewModel vm in MainViewModelList)
    {
        vm.MyProperty = (bool)val;
    }
}



At the end, it's not working because I'm making a loop !!!!

What I have tried:

See the content of the message describing what I have tried.
Posted
Updated 11-Sep-18 12:35pm

1 solution

The INotifyPropertyChanged is intended to communicate from a ViewModel to the View, and uses a lot of external logic. You could do all the stuff with creating a Binding, but it would probably be far easier to just have the model execute an event whenever a change occurs that is observed by both ViewModels. When a ViewModel is notified of the change it ensures that its value corresponds to the new value in the Model.

Another thing you could do is have a reference in both ViewModels to a class that contains the properties that the two Views share, and that way when one view makes a change, it is changing the value in this common class, and that property, when changed executes the PropertyChanged event.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900