In my MVVMC application I have a process which contains multiple steps, basically a wizard.
My controller resolves my outer View (call it WizardView
) and adds it to the main region.
WizardView
contains a breadcrumb trail to show the progress through the wizard and a sub Region to load other views into (call this WizardRegion
). Step1View
is the first View loaded into WizardRegion
.
Each view has it's ViewModel injected into the constructor using the Unity container.
WizardViewModel
subscribes to several event aggregation events which are published by the step view models.
As each step is completed the View Model publishes an event which WizardViewModel
uses to store the state, this means WizardViewModel
is collecting the data from each step as we progress. The step ViewModel also calls the controller to load the next step into WizardRegion
.
At the final step WizardViewModel
saves the result of the wizard and the MainRegion
is navigated back to some other screen.
The next time we enter the wizard, we create a new instance of all the Views and ViewModels but the event subscriptions from the previous wizard still exist.
How can I make my view models aware that they're de-activated so I can unsubscribe my events?
Another option would be to unsubscribe from the event in the event handler. This will probably work but will add complexity when I step back in the wizard and need to re-subscribe to the events again.
The solution is to implement Microsoft.Practices.Prism.IActiveAware
in my View Model.
public bool IsActive
{
get { return _isActive; }
set
{
if (_isActive != value)
{
_isActive = value;
DoActiveChangedWork(value);
}
}
}
public event EventHandler IsActiveChanged;
It's also possible to implement this in the View but it's not a requirement.