I have two ViewModels one is attached to a main window and the other is attached to child window that is opened by clicking on a button on the main window. The child window contains a list of items and I want to select an item and display it in the main window by updating the main window viewmodel. What is the best way to accomplish this. Thanks!
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
The standard way to communicate between ViewModels is to use Messaging of some sort. One good implementation of this is the MVVM Light Toolkit
Here's some (random) code using the default messenger therefrom:
There are any number of ways to do this.
Pass a reference to the main/parent view model into the child and have the child call the main view model.
Have the child view model fire an event that the parent subscribes to.
Use a messenger/mediator to communicate between the two. The parent subscribes, the child posts the message. This provides loose coupling.
Set the main view model up as a global service. Register it somehow. Have the child look up the service (requiring global services is a pretty common problem) and then call something on the global/common interface.
From my experience, the simplest method would be #2. Define an event on the child view model. The parent will have to look up the child (I don't know if it contains it or how your view models are constructed) and subscribe to the event.
I think best way to pass the message between two view models is event programming.
Best way to do it is to have some kind of reference from child to parent and to update this parent when closing the child.
Or you can have some kind of event on child and let parent listen on this event. You then raise this event when child closes.
Messaging is used when both ViewModels are logicaly unrelated.
[rant] Dont people even know basic principles of OOP or what?? [/rant]
I had the same problem a few days before ;-)
Finally I used a mediator to communicate both view-models. On fact I used the Messenger from MVVM Light.
After that I defined the Message with everything I needed to know from main window:
Finally the message back from the childwindow you only have to register the message with result and the object you want to get back.
You should register from the code-behind of your view to close the window.