MVVM Foundation: How to close Application Window f

2019-05-23 21:50发布

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}" />  
    

2条回答
贪生不怕死
2楼-- · 2019-05-23 22:10

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.

查看更多
The star\"
3楼-- · 2019-05-23 22:15

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.

查看更多
登录 后发表回答