MVVM messaging or events or what other option out

2019-03-04 00:38发布

问题:

I have a menu in MainViewModel, now on selection of a particular menuItem I wanted to update data of a view which is already loaded.

i.e. although there's an instance of that viewModel in MainViewModel, when I try to invoke the method thru that instance and change the data property, it doesnt show the changes in the view. Whereas same changes occur when I invoke that method through relay command using a button on that viewModel's view.

Now its like I need to invoke relay command of that viewModel from MainViewModel, I guess that will fix the problem, but how to do that? what's easiest way. Will i need to use messaging?

回答1:

I tried MVVM Light messenger class, its quite straightforward and elegant (keeps ViewModels loosely coupled)!! and most importantly it works

code:

Send:
Messenger.Default.Send(stringParameter, "key_anything");

Register:
Messenger.Default.Register<string>(this, "key_anything", invokeFunction);

private void invokeFunction(string stringParamter)
{
//code goes here!
}