MVVM light - how to access property in other view model

a 夏天 提交于 2019-12-17 06:11:14

问题


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


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/2699328/mvvm-light-how-to-access-property-in-other-view-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!