谁负责 MVVM 模式中的窗口视图生命周期? [英] Who is responsible for Window View lifecylce in MVVM pattern?

查看:70
本文介绍了谁负责 MVVM 模式中的窗口视图生命周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不清楚谁在 WPF 中创建和处理窗口.
我们知道窗口可以通过单击右上角的十字符号关闭,我们只能通过在 Closing 事件处理程序中设置 Cancel = true 来停止关闭.
对我来说,ViewModel 决定是否允许关闭 View 是很自然的.我认为是 VM 请求适当窗口的实例化.
在我们的项目中,我们创建了 IViewManager:

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();
}

所以我们的虚拟机通过绑定和间接通过 IViewManager 与视图通信.在我目前看到的 MVVM 应用程序示例中,VM 是非常被动的,并且不负责 View 的生命周期.这就是为什么我对我们的设计有些怀疑.
我不能确定我们没有遗漏一些关于 MVVM 模式的重要内容.

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.

推荐答案

为此,您必须修改您的 Window 以具有将绑定到您的 ViewModel(this属性会说明是否有任何挂起的更改.现在如果 CanSavetrue,您将向用户显示一个对话框,上面写着 您想保存挂起吗?更改" 并且如果用户单击 触发与您的 保存按钮 相同的命令,如果用户单击 只需简单地关闭窗口.如果 CanSavefalse,只需关闭窗口.我希望这会给你一个想法.

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.

另一种方法是自定义窗口关闭按钮并通过命令将其绑定到 ViewModel 并从那里处理它.

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

这篇关于谁负责 MVVM 模式中的窗口视图生命周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆