Who is responsible for Window View lifecylce in MV

2019-06-09 08:46发布

It stays for me unclear who creates and disposes windows in WPF.
As we know window can be closed by clicking the cross sign in the upper right corner and we can stop closing only by setting Cancel = true in Closing event handler.
For me it is quite natural for the ViewModel to decide if View is allowed to close. And I think it is VM whow request the instantiation of the appropriate window.
In our project we created IViewManager:

public interface IViewManager
{
    void ShowView();
    void CloseView();
}

public interface IWindowedViewModel : IDisposable
{
    bool IsEnabled {get;set;}
    WindowState WindowState {get;set;}
    Visibility Visibility {get;set;}
    bool IsActive {get;set;}

    bool CanBeClosed();
}

So our VMs communicate with the view via bindings and indirectly via IViewManager. In the examples of MVVM applications I've seen so far VM is quite passive and is not responsible for View's lifecyle. That's why I have some doubts about our design.
I wan't to be sure we are not missing something important concerning MVVM pattern.

标签: wpf mvvm
1条回答
兄弟一词,经得起流年.
2楼-- · 2019-06-09 09:29

For that you will have to Modify your Window to have bool type Depedency Property like CanSave that will be bound to your ViewModel(this Property will say whether ther are any pending changes or not).Now if CanSave is true you will show user a DialogBox which says "Do you want to Save pending changes" and if User Click Yes fire the Same Command as that is for your Save Button , If user clicks No Just simply close the window.And if CanSave is false simply close the window.I hope this will give you an idea.

Another way to do that is Make Window Close Button Custom and bind it to ViewModel through Command and handle it From there.

查看更多
登录 后发表回答