ernest
ernest

Reputation: 1724

What would be the best way to raise a MVVM property from a different ViewModel?

On my MainViewModel, I have a property that looks like this:

private bool _IsSkinNight = true;
    public bool IsSkinNight
    {
        get { return _IsSkinNight; }
        set 
        {
            _IsSkinNight = value;

            RaisePropertyChanged("IsSkinNight");
            RaisePropertyChanged("WindowBackColor");
            RaisePropertyChanged("StyleImage");
        }
    }

As you can see, I use this one property to raise other properties. It makes changing the UI much easier. Especially as I am going to add more items to it.

However, I have a property on a WPF page that I need to update as well. But since it's on a different page, its ViewModel is separate as well. So this property can't call RaisePropertyChanged on it and the property in the page can't check the state of IsSkinNight.

So what would be the best way to cross between the different ViewModels? I'll be adding more pages. So is there a way to make like a universal property that all ViewModels can access?

Thanks

Upvotes: 0

Views: 210

Answers (3)

RoelF
RoelF

Reputation: 7573

In such a case, I sometimes create a kind of Context class, to keep track of "global" properties. This class has to be registered as a Singleton.

public class SkinContext : ISkinContext {
    private bool _IsSkinNight = true;
    public bool IsSkinNight
    {
        get { return _IsSkinNight; }
        set 
        {
            _IsSkinNight = value;

            RaisePropertyChanged("IsSkinNight");
            RaisePropertyChanged("WindowBackColor");
            RaisePropertyChanged("StyleImage");
        }
    }

then I inject this class in each ViewModel that needs to be aware of the context and subscribe to the NotifyPropertyChanged event (Or a custom event that you created):

public class SomeViewModel {
    public SomeViewModel(ISkinContext context){
        context.OnPropertyChanged += (s,e) => { /*Raise other notification and whatnot*/ }
    }
}

Upvotes: 0

ernest
ernest

Reputation: 1724

Thanks for the help everyone. I did a bit more research, based on the suggestions here, and came across MVVM Messages.

Using this blog post, I was able to use MVVM messages to achieve my goal. Thanks again.

Upvotes: 0

Miiite
Miiite

Reputation: 1557

Even if I don't like using it, you probably need to look up for EventAgregators.

Basically you will be able to fire an event in your MainViewModel, and in your other view models you will be able to register to one or more event of this agregator.

However, I strongly recommend that you use it very lightly, because it can become extremely difficult to Debug, since there is no call stack when you fire an event like that.

Upvotes: 3

Related Questions