Capturing the OnExit event in WPF with MVVMCross

744 views Asked by At

I need to explicitly close and dispose of a SerialPort object when my MVVMCross WPF application exits, i.e. when the red X is clicked. In order to do this, I need to call a method of the current ViewModel.

I have been trying to do this by following the MVVMCross n=42 video and adding an IKillable interface with a public abstract void KillMe() method in an abstract BaseViewModel class that implements IKillable. Then, in the WPF project I added a BaseView class, exactly as he does in the video. I am able to access methods of the current view model at this point.

In the video, the examples are IOS, Droid, and Windows Phone, where one can override events such as OnNavigatedTo, etc. In WPF, there is no OnExit() which I could override available in the BaseView class.

I am wondering, is there any way that I can call this method of the current view model when the application exits? I am able to do this:

protected override void OnExit(ExitEventArgs e)
{
    // Do Something
    base.OnExit(e);
}

in the App.Xaml.Mvx.cs class that came with the MVVMCross Nuget package, and I believe that this is the right place to put the code I want to execute when the program exits. The problem is that I do not have any reference to the current viewmodel.

If anyone could help me out I would really appreciate it. Thanks!

EDIT/UPDATE:

I found a work around, it seems somewhat "hacky" but it gets the job done. The class which holds the reference to the SerialPort I need to close is registered as a singleton within MVVMCross. So, I added a field of the interface type of that singleton to the App.Xaml.Mvx.cs class, then at the end of DoSetup(), I call Mvx.Resolve<>(); on that type and assign that result to the field I created. Then, I have the protected override void OnExit(ExitEventArgs e), where I can call the Close() and Dispose() methods on the field. This does what I need it to do.

I am still interested if there is a better, "more correct" way to do it with MVVMCross, however.

1

There are 1 answers

0
Michal Kania On

If you close an app the OnSuspending method is called and there I would write code for a SerialPort and because you want to fire a method of current ViewModel I would just have object representing current ViewModel in the App.xaml.cs so I can call method of it inside OnSuspending()

I would do it this way, but I don't know if it's better or can do what you need. But maybe it will give you an idea.