实现“关闭窗口"使用 MVVM 命令 [英] Implementing "close window" command with MVVM

查看:27
本文介绍了实现“关闭窗口"使用 MVVM 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的第一次尝试在后面的代码中完成了所有工作,现在我正在尝试重构我的代码以使用 MVVM 模式,遵循 MVVM 在框中信息.

So my first attempt did everything out of the code behind, and now I'm trying to refactor my code to use the MVVM pattern, following the guidance of the MVVM in the box information.

我已经创建了一个视图模型类来匹配我的视图类,我正在将代码从后面的代码移到视图模型中,并从命令开始.

I've created a viewmodel class to match my view class, and I'm moving the code out of the code behind into the viewmodel starting with the commands.

我的第一个障碍是尝试实现一个关闭"按钮,如果数据未被修改,该按钮将关闭窗口.我已经设置了一个 CloseCommand 来替换 'onClick' 方法,除了代码试图运行 this.Close() 的地方外,一切都很好.显然,由于代码已从窗口移至普通类,因此this"不是窗口,因此不可关闭.但是,根据 MVVM,视图模型不知道视图,因此我无法调用 view.Close().

My first snag is trying to implement a 'Close' button that closes the window if the data has not been modified. I've rigged up a CloseCommand to replace the 'onClick' method and all is good except for where the code tries to run this.Close(). Obviously, since the code has been moved from a window to a normal class, 'this' isn't a window and therefore isn't closeable. However, according to MVVM, the viewmodel doesn't know about the view, so i can't call view.Close().

有人可以建议我如何从 viewmodel 命令关闭窗口吗?

Can someone suggest how I can close the window from the viewmodel command?

推荐答案

您不需要将 View 实例传递给您的 ViewModel 层.您可以像这样访问主窗口 -

You don't need to pass the View instance to your ViewModel layer. You can access the main window like this -

Application.Current.MainWindow.Close()

如上所述,我认为在 ViewModel 类中访问主窗口没有问题.根据 MVVM 原则,您的 View 和 ViewModel 之间不应紧密耦合,即它们应该在工作时忽略其他操作.在这里,我们没有从 View 向 ViewModel 传递任何东西.如果您想寻找其他选项,这可能对您有所帮助 - Close window using MVVM

I see no issue in accessing your main window in ViewModel class as stated above. As per MVVM principle there should not be tight coupling between your View and ViewModel i.e. they should work be oblivious of others operation. Here, we are not passing anything to ViewModel from View. If you want to look for other options this might help you - Close window using MVVM

这篇关于实现“关闭窗口"使用 MVVM 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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