Simple EventAggregator class using Rx.
To install library by using Nuget package manager execute next command:
Install-Package EventAggregatorRx -Version 1.0.0.1
Design events using IEvent interface.
public class ItemAdded : IEvent
{
public Guid ItemId {get; set;}
}
Next step, implement your events in the viewModel and subscribe.
public class BasketViewModel : IEventHandler<ItemAdded>
{
...
public BasketViewModel(IEventAggregator event)
{
eventAggregator.Subscribe(this); //subscribing viewmodel
}
public void Handle(ItemAdded @event)
{
//TODO: Any action
}
}
Next step: Publish the event in another viewmodel.
public class CatalogViewModel
{
...
public CatalogViewModel(IEventAggregator eventAggregator)
{
eventAggregator.Publish(new ItemAdded {ItemId = Guid.NewGuid()});
}
}
You can use method extensions to simplify
public class CatalogViewModel
{
...
public CatalogViewModel(IEventAggregator eventAggregator)
{
eventAggregator.Publish<ItemAdded>(x => ItemId = Guid.NewGuid());
eventAggregator.Publish<ItemAdded>(); //If the event no has data
}
}