I have a simple ViewModel
public class TestViewModel : ViewModelBase, IDisposable
{
public TestViewModel()
{
Messenger.Default.Register<string>(this, MessageHandling);
}
public void MessageHandling(string message)
{
System.Windows.MessageBox.Show(message);
}
public override void Cleanup()
{
Messenger.Default.Unregister(this);
base.Cleanup();
}
}
And i use it in my XAML like this:
<Window.Resources>
<ResourceDictionary>
<vm:TestViewModel x:Key="ViewModel"></vm:TestViewModel>
</ResourceDictionary>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource ViewModel}}">
</Grid>
Can anyone help we with disposing of this ViewModel, by disposing i mean on which event should i subscribe to call VM method cleanup? Because if I don’t do Cleanup the ViewModel remains in memory and still handles messages.
I hope i explained it properly 🙂
Thanks in advance
First of all it depends on you when you want to dispose it. You didn’t make that clear. I first thought you meant “When the application closes” then i would use the exit event. But i got irritiated by your statement
What can only happen if you want to dispose but your application still needs to run. If your application closes, nothing stays in memory and no messages are handled anymore. But its still good practice to not rely on that.
So if you meant “when the application closes” this is your answer.