Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVVM light - how to access property in other view model

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

like image 282
Ueli Sonderegger Avatar asked Apr 23 '10 14:04

Ueli Sonderegger


People also ask

How do you pass data from ViewModel to ViewModel?

Here, the Main View contains an instance of a Detail View. The Views' DataContexts are the MainViewModel and DetailViewModel respectively. To pass data from the Main View/Main ViewModel to the Detail ViewModel, assign the data to the ViewModelExtensions. Parameter attached property on the Detail View instance.

How do I link views and ViewModel?

The other approach to bind the View and Viewmodel in View First Approach is in the xaml itself as shown in the figure below. I am setting the datacontext in the . xaml of the View itself. To set the datacontext in this way the ViewModel class need to have a default constructor.

What is the difference between the MVVM Cross and MVVM Light?

MvvmCross has some setup code provided by the framework, and inside this setup code you initialize the content of the IoC container. MVVM Light, on the other hand, relies on you doing this inside your own app code.


2 Answers

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

like image 169
CodeWeasel Avatar answered Oct 01 '22 10:10

CodeWeasel


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

like image 35
LBugnion Avatar answered Oct 01 '22 09:10

LBugnion