How do I notify a parent view of a child view event in an MVVM WPF application?

谁都会走 提交于 2019-12-09 21:40:03

问题


I have an MVVM based WPF desktop application. I'm utilizing MVVMLight and Prism to create user controls which contain views and sub-views.

I have button on a child view. (Let's say it's a close button)

What is the best way to propagate notification of the click event from the nested child view up to it's containing parent view?


回答1:


The child view could use the EventAggregator in Prism or the Messenger class in MvvmLight to send a message that the parent view (or view model) subscribes to. Please refer to the following links for more information about the concept.

https://msdn.microsoft.com/en-us/magazine/jj694937.aspx http://dotnetpattern.com/mvvm-light-messenger https://blog.magnusmontin.net/2014/02/28/using-the-event-aggregator-pattern-to-communicate-between-view-models/

Another approach would be to keep a strong reference to the child view model from the parent view model and raise an event in the child that the parent subscribes to.

The benefit of using an event aggregator or a messenger is that you avoid introducing a tight coupling between publisher of the event and the subscriber which should make the application easier to maintain.

Both the publisher and the subscriber of the event or message knows only about the event aggregator or messenger but they don't know anything about each other.




回答2:


With Prism EventAggregator.

1. Make event that you want to publish

public class CloseTabEvent : PubSubEvent<TPayload>
    {

    }

where TPayload is type you are passing(int, string, or even class object)

2. In your subView where your close button is, publish that event. In your close button Command (execute method) u publish that event.

private void OnCloseExecuted(object obj)
{
_eventAggregator.GetEvent<CloseTabEvent>().Publish(SomethingThatYouPublis..ThisIsTPayload);
}

In your subView constructor pass IEventAggregator and make a private field.

private IEventAggregator _eventAggregator;
public SubViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
}

3. In your mainViewModel you also pass IEventAggregator and subscribe inside constructor.

public MainViewModel((IEventAggregator eventAggregator)
{
    eventAggregator.GetEvent<CloseTabEvent>
   ().Subscribe(MethodForClosingThatSpecificTab);
}

And that's it.

IMPORTANT: When resolving IEventAggregator with some IoC(Unity, Autofac..) make it singleton, so it's one for whole app.



来源:https://stackoverflow.com/questions/43482545/how-do-i-notify-a-parent-view-of-a-child-view-event-in-an-mvvm-wpf-application

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