实施“关闭窗口". MVVM命令 [英] Implementing "close window" command with MVVM

查看:87
本文介绍了实施“关闭窗口". 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.

我已经创建了一个viewmodel类来匹配我的view类,并且我将从命令开始将代码从后面的代码移到viewmodel中.

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.如果您想寻找其他选项,可能会对您有所帮助-使用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天全站免登陆