Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutting down and cleaning up Views from a ViewModel

Tags:

c#

mvvm

wpf

xaml

My application creates a number of child Views using a variant of the famous IDialogService. I now have a requirement to enable shutting down these Views on a programmatic basis, when a specific event or set of events occurs.

Firstly, how best should I expose the Views' Close method, bearing in mind that

  1. The View's DataContext (ViewModel) has to be disposed and
  2. View.Dispatcher.InvokeShutdown must be called for each View that is being closed.

So far, I have a mixture of attached behaviours to hook into the Closing event to handle cleaning up and an Action on the ViewModel like

vm.OnCloseAction = ()=> view.Close();

to handle actually closing the View from a ViewModel.

This doesn't feel particularly elegant to me, though. Does anyone have any other ideas or alternative approaches?

like image 948
gͫrͣeͬeͨn Avatar asked Jan 24 '26 10:01

gͫrͣeͬeͨn


1 Answers

One idea would be to use whatever Messaging framework you're using (like the Messenger in MVVM Light, which is what I use), set up a Closing message (or something like that) and have anything that needs to do something on close Register for that Closing message.

like image 179
Tim Avatar answered Jan 25 '26 22:01

Tim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!