Reputation: 4359
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?
Upvotes: 2
Views: 1443
Reputation: 1064
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.
Upvotes: 1