15

I'm using mvvm light to build a Silverlight application. Is there a code snippet that shows how to access a view model's property or command from within another view model or user control's code behind?

I guess it's simple, but I somehow missed something.

Ueli

Ueli Sonderegger
  • 153
  • 1
  • 1
  • 6
  • It depends on the implementation of your controls. Are you sharing the ViewModel between views that are under a parent view or are you simply trying to share the property/Command between two independent views? – Jeff Wain Apr 23 '10 at 15:29
  • The view in question can be nested in different views but it relays on a viewmodel that needs to be able to access a property from an independent viewmodel. In my concrete case it's a CardViewModel that needs to grab an information about the currently logged in user (handled and stored in an independent UserViewModel) to make a call to a webservice. – Ueli Sonderegger Apr 23 '10 at 15:48

3 Answers3

34

You could use the Messenger to do this: Send the user in the UserViewModel:

Messenger.Send<User>(userInstance);

would just send the user to anyone interested.

And register a recipient in your CardViewModel:

Messenger.Register<User>(this, delegate(User curUser){_curUser = curUser;});

or you can also send a request from your CardViewModel for shouting the user:

Messenger.Send<String, UserViewModel>("Gimme user");

And react on that in the UserViewModel:

Messenger.Register<String>(this, delegate(String msg)
{
if(msg == "Gimme user")
Messenger.Send<User>(userInstance);
});

(You better use an enum and not a string in a real scenario :) )

Perhabs you can even response directly but I can't check it at the moment.

Just check this out: Mvvm light Messenger

CodeWeasel
  • 691
  • 8
  • 12
  • Perfect, that's what I needed. (and now it seems so obvious that it makes me feel like an idiot...). Dankä ond n Gruess us Brasilie. – Ueli Sonderegger Apr 24 '10 at 14:24
4

Another way is to use the overload of RaisePropertyChanged that also broadcasts the change. You would do this:

RaisePropertyChanged(() => MyProperty, oldValue, newValue, true);

Then in the subscriber:

Messenger.Default.Register<PropertyChangedMessage<T>>(this, Handler);

where T is the type of MyProperty.

Cheers Laurent

LBugnion
  • 6,672
  • 2
  • 24
  • 28
0

Another way to look at the problem is to have a service that returns the "currently logged in user".

The responsibility of handling who's logged in is more the responsibility of a service anyway, and the ViewModels stay simple.

ViewModels should exist only for the View. But, being good citizens, they can also provide help to other ViewModels like Laurent and CodeWeasel are showing.

Patrice Calvé
  • 674
  • 6
  • 12