Kelly
Kelly

Reputation: 7193

How to run code on your ViewModel using Caliburn.micro when a window is closing

I'm new to using Caliburn.micro. I have a simple app that starts a process running in the ViewModel listening for some network messages. When the window closes I would like to stop the process in the Viewmodel from listening any longer.

Since the view is a UserControl how can I tell the window is closing so my ViewModel can clean up correctly?

Upvotes: 0

Views: 801

Answers (2)

Mare Infinitus
Mare Infinitus

Reputation: 8192

In addition to what "Trust me - I'm a Doctor" said I would recommend to have a look on IDeactivate interface.

You can implement that interface, have a Deactivate method and implement everything you need there.

Caliburn documentation on lifecycle

Upvotes: 1

Patryk Ćwiek
Patryk Ćwiek

Reputation: 14328

You can override OnDeactivate if your view model implements IScreen (or, equivalently, inherits from Screen if you want to have some logic ready). That method will be called when the screen gets deactivated, there's also the bool flag if the screen is only deactivating or closing.

Mind you, only the view models coming from your IoC container of choice in the bootstrapper are going to have their lifetimes correctly hooked up. So if you get the VM that way, it will properly have the OnInitialize, OnActivate and OnDeactivate called. If you instantiate the view model in any other way (e.g. manually) and you're using them in e.g. Conductor, you're out of luck...

Although I think that if you're using IWindowManager with view model implementing IScreen, it will try to enforce the regular lifetime cycle.

Upvotes: 2

Related Questions