Josh Close
Josh Close

Reputation: 23383

ViewModel Event Communication

I have a WP7 app I'm creating and I want a login screen to appear if the user hasn't logged in yet. I have Main.xaml which has a view model MainViewModel.cs. For the login or signup portions I have them embedded as a Grid in Main.xaml, but I would think having them as a user control would work fine also. The login and signup portions will have their own view model, possibly the same one for both, AccountViewModel.cs, that the Grid or user control has it's DataContext set to.

After the user signs up or logs in, which occurs in AccountViewModel.cs, what is the best way for MainViewModel.cs or Main.xaml to know that it is complete, and it can begin loading data, or doing whatever it needs to do?

My initial thought is to use MVVM Light's messaging system. After signup/login occurs, broadcast a message that it's complete, and MainViewModel.cs will be registered to the message and can act on it.

Is there another way or more proper way of letting Main know something has occurred in it's child?

If this is too hard to follow I can add code examples.

Upvotes: 1

Views: 319

Answers (2)

LBugnion
LBugnion

Reputation: 6662

Another approach would be to store this kind of info (IsLoggedIn) in a "global view model" such as SettingsViewModel.Instance for example. For a viewmodel of global meaning like Settings, it is an approach that makes a lot of sense IMHO. If you make this property raise the PropertyChanged event, this allows you to dynamically modify the UI when the property changes, and hide the login UI smoothly for instance.

cheers, Laurent

Upvotes: 0

Derek Lakin
Derek Lakin

Reputation: 16319

A messaging system, such as the one in MVVM Light is a great way to decouple these kind of actions and provide notifications in the way you describe. Can't say as I'd advocate anything else really. The Prism library provides an EventAggregator, which does the same thing, but if you're already using MVVM Light, then stick with that.

Upvotes: 2

Related Questions