简体   繁体   中英

How to implement Close button in MVVMCross WPF application?

I am using MVVMCross in my WPF application, and I want to provide a Close (or Exit ) button in the GUI to shut-down the entire application. Is there a straightforward way to do this using MVVMCross functionality?

I have tried the following approach with my MainViewModel :

public class MainViewModel : MvxViewModel
{
    private MvxCommand _closeCommand;
    public MvxCommand CloseCommand {
        get { 
            return _closeCommand ?? (_closeCommand = new MvxCommand(DoClose));
        }
    }

    public void DoClose() {
        Close(this);
    }
}

Unfortunately, to no avail. The DoClose method does get called when I press a button that has been bound to CloseCommand , but the view-model (and corresponding view) fail to close, even when the WPF App StartupUri is set to the MainView .

Many MvvmCross platforms don't support applications closing themselves - this is frowned upon behaviour in iOS, WindowsPhone, Android, WindowsPhone, etc - it isn't supported by public APIs there - so this isn't a common cross-platform request.

However, if you wanted to implement this functionality for those platforms that do support it, then I think perhaps the best place to put this would either be in the presenter or in a custom UI-injected service.


To put it in a custom presenter, simply:

  • create a custom presenter class (based on MvxWpfViewPresenter.cs )
  • return an instance of this class in an override of the CreatePresenter method in your your Setup.cs
  • override the ChangePresentation method in your custom presenter - this method could perhaps use the 'well-known' MvxClosePresentationHint.cs which is what Close sends or it could use a new custom presentation hint you define and send via ChangePresentation(MvxPresentationHint hint) in a ViewModel.

To put this functionality instead in some custom UI service, see N=31 in http://mvvmcross.wordpress.com/


If you are looking at this shutdown area, then you may also want to consider what steps to take when an application is shutdown (either through user or operating system action). MvvmCross does expose the beginnings of common 'lifetime monitor' hooks within the framework, but actually in practice these are very basic at present - so you may find you need to build your own common layer here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM