Launch View Models Activation in Prism / Composite MVVM WPF Application
In my MVVMC application, I have a process that contains several steps, mostly a wizard.
My controller resolves my appearance (calls it WizardView
) and adds it to the main area.
WizardView
contains a search track to show progress through the master and sub-region to download other views (name it WizardRegion
). Step1View
is the first view uploaded to WizardRegion
.
In each view, it injects the ViewModel into the constructor using the Unity container.
WizardViewModel
subscribes to multiple event aggregation events that are published to step view models.
As each step completes, the view model publishes an event that it WizardViewModel
uses to store state, which means it WizardViewModel
collects data from each step as it progresses. The ViewModel step also calls the controller to load the next step into WizardRegion
.
At the last step WizardViewModel
, the result of the wizard is saved, and MainRegion
it goes to another screen.
The next time we enter the wizard, we create a new instance of all Views and ViewModels, but the event subscriptions from the previous wizard still exist.
How can I represent my view models that they are deactivated so I can unsubscribe from my events?
Another option is to unsubscribe from the event in the event handler. This will probably work, but will add complexity when I return to the wizard and need to subscribe to events again.
source to share
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;
This can also be implemented in the view, but this is not a requirement.
source to share
If you are talking about Prism EventAggregator - you can set the parameter keepSubscriberReferenceAlive
to false
so that it uses a weak reference under the hood so that everything will be automatically canceled by GC when the object "dies".
fundAddedEvent.Subscribe(FundAddedEventHandler, ThreadOption.UIThread, true);
otherwise, you have to do it yourself by explicitly unsubscribing:
fundAddedEvent.Unsubscribe(FundAddedEventHandler);
source to share