2

I have three ViewModels: - MainViewModel, - NavigatorViewModel, - ProjectViewModel.

In the MainViewModel I have a property called CurrentProject from type ProjectViewModel:

public ProjectViewModel CurrentProject
    {
        get
        {
            return _currentProject;
        }
        set
        {
            if (_currentProject == value)
            {
                return;
            }
            _currentProject = value;
            RaisePropertyChanged("CurrentProject");
        }
    }

In the NavigatorViewModel I have also a property CurrentProject

public ProjectViewModel CurrentProject { get { return ViewModelLocator.DesktopStatic.CurrentProject; } }

I use MVVM light. The View NavigatorView doesnt get notified if the property CurrentProject in the MainViewModel is changed.

How can I let the NavigatorView know, that the property has changed?

Kevin
  • 190
  • 12

1 Answers1

0

As a design concern, I would recommend not using a static Singleton pattern for this. You could use the Messenger class to send messages.

However, to address your current problem, you need to respond to the PropertyChanged event on the Singleton for that property:

public class NavigatorViewModel : INotifyPropertyChanged
{
    public NavigatorViewModel()
    {
        // Respond to the Singlton PropertyChanged events
        ViewModelLocator.DesktopStatic.PropertyChanged += OnDesktopStaticPropertyChanged;
    }

    private void OnDesktopStaticPropertyChanged(object sender, PropertyChangedEventArgs args)
    {
        // Check which property changed
        if (args.PropertyName == "CurrentProject")
        {
            // Assuming NavigatorViewModel also has this method
            RaisePropertyChanged("CurrentProject");
        }
    }
}

This solution listens for changes to the Singleton property and propagates the change to listeners of NavigatorViewModel.

Warning: Somewhere in the NavigatorViewModel you need to unhook the event or you risk a memory leak.

ViewModelLocator.DesktopStatic.PropertyChanged -= OnDesktopStaticPropertyChanged;
Ed Chapel
  • 6,842
  • 3
  • 30
  • 44
  • Thank you very much! It works pretty good. Do you have an article about using the Messenger in the same way? I can't imagine how this works. I personally used it only in Messaging between View and Viewmodel. Do you mean that if I Change the property that I have to submit a message? – Kevin Sep 08 '13 at 13:44
  • Take a look at http://stackoverflow.com/questions/2911171/mvvm-light-messenger-class. – Ed Chapel Sep 08 '13 at 13:52
  • Also, if that helps, please mark the answer as the solution. Cheers. – Ed Chapel Sep 08 '13 at 13:52