Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

notify View(Models) of closing the program

So I got my prism/mvvm/mef program running nicely along, the user is entering data in the application, then closes the application (or shuts down the computer).

How can I get my View(Model) notified of the program closing / the computer shutdown, so it can either save the users data or maybe ask if these should be saved?

Losing data on program close is definitely something to be avoided, and it does not make sense to save stuff on every single keypress of the user.

like image 438
Sam Avatar asked Dec 16 '10 09:12

Sam


1 Answers

I expose CompositeCommands that clients can register to for interesting global "events", e.g.

public static class HostCommands
{
    private static readonly CompositeCommand Shutdown = new CompositeCommand();

    public static CompositeCommand ShutdownCommand
    {
        get { return Shutdown; }
    }
}

I trigger the shutdown command in my shell, e.g.

public Shell()
{
    InitializeComponent();

    Closing += (sender, e) =>
    {
        if (HostCommands.ShutdownCommand.CanExecute(e))
            HostCommands.ShutdownCommand.Execute(e);
    };
}

And clients can register as follows, e.g

public SomeViewModel(IEventAggregator eventService)
{
    //blah, blah, blah...

    HostCommands.ShutdownCommand.
        RegisterCommand(new DelegateCommand<object>(_ => Save()));
}

Update

I do not handle the cancel scenario, but you could implement this via the object which is passed to the command. For instance in the above code I pass in a CancelEventArgs which clients could manipulate i.e. by setting Cancel=true. I could inspect this value in my Shell closed event handler after the command has execute to derive whether I should cancel closing the shell. This pattern can be expanded on.

like image 157
Tim Lloyd Avatar answered Sep 28 '22 04:09

Tim Lloyd