WPF MVVM UserControl Binding "Container", dispose to avoid memory leak.
- by user178657
For simplicity.
I have a window, with a bindable usercontrol
<UserControl Content="{Binding Path = BindingControl, UpdateSourceTrigger=PropertyChanged}">
I have two user controls, ControlA, and ControlB, Both UserControls have their own Datacontext ViewModel, ControlAViewModel and ControlBViewModel.
Both ControlAViewModel and ControlBViewModel inh. from a "ViewModelBase"
public abstract class ViewModelBase : DependencyObject, INotifyPropertyChanged, IDisposable........
Main window was added to IoC... To set the property of the Bindable UC, i do
ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlA;
ControlA, in its Datacontext, creates a DispatcherTimer, to do "somestuff"..
Later on., I need to navigate elsewhere, so the other usercontrol is loaded into the container
ComponentRepository.Resolve<MainViewWindow>().Bindingcontrol= new ControlB
If i put a break point in the "someStuff" that was in ControlA's datacontext. The DispatcherTimer is still running...
i.e. loading a new usercontrol into the bindable Usercontrol on mainwindow does not dispose/close/GC the DispatcherTimer that was created in the DataContext View Model...
Ive looked around, and as stated by others, dispose doesnt get called because its not supposed to...
:)
Not all my usercontrols have DispatcherTimer, just a few that need to do some sort of "read and refresh" updates./.
Should i track these DispatcherTimer objects in the ViewModelBase that all Usercontrols inh. and manually stop/dispose them everytime a new usercontrol is loaded? Is there a better way?