MVVM Foundation: How to close Application Window from ViewModel

你离开我真会死。 提交于 2019-12-07 21:09:36

问题


I am using MVVM Foundation but I think its quite straight-forward and not really framework specific. My setup is as follows:

  • StartViewModel - has a ExitCommand that returns a RelayCommand/ICommand

    public ICommand ExitCommand {
        get { return _exitCommand ?? (_exitCommand = new RelayCommand(() => MessageBox.Show("Hello World"))); }
    }
    public RelayCommand _exitCommand;
    
  • StartView (User Control) has a button binded to the ExitCommand

    <Button Content="Exit" Command="{Binding ExitCommand}" />  
    

回答1:


First, read as much as you can stomach on MVVM, e.g. WPF Apps With The Model-View-ViewModel Design Pattern on MSDN. Once you understand the basic principles driving it the answer will seem more reasonable.

Basically you want to keep your View (UI) and ViewModel (essentially abstract UI, but also abstract Model) layers separate and decoupled. Showing a message box or closing a window should be considered a UI specific detail and therefore implemented in the View, or in the case of a message box, more generally available via a 'Service'.

With respect to the ViewModel, this is achieved using Inversion of Control (IoC). Take the message box example above. Rather than showing the message box itself, it takes a dependency on an IMessageBoxService which has a Show method and the ViewModel calls that instead - delegating responsibility. This could be taken further by leveraging Dependency Injection (DI) containers.

Another approach used for closing a View window might be for the ViewModel to expose an event, called for example RequestClose (as in the MSDN article), that the View subscribes to. Then the ViewModel would raise the event when it wants the corresponding View / window to close; it assumes something else is listening and will take responsibility and actually do it.




回答2:


you can implement an CloseEvent in your StartViewModel. in your StartView you have to register this CloseEvent. when you Raise your closeevent from your VM then, your View recognize that it has to close your app/window.



来源:https://stackoverflow.com/questions/3791677/mvvm-foundation-how-to-close-application-window-from-viewmodel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!