WPF(MVVM):从Viewmodel关闭视图吗? [英] WPF (MVVM): Closing a view from Viewmodel?

查看:161
本文介绍了WPF(MVVM):从Viewmodel关闭视图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人遇到过使用MVVM在视图模型中关闭视图的聪明方法吗?

Anybody come across a clever way of closing a view in a viewmodel using MVVM?

也许有一种使用绑定的方式来通知视图(窗口)关闭的方法吗?

Maybe there is a way of using binding to signal the view (window) to close?

我真的很感谢任何人的任何投入.

I would really appreciate any input anyone has.

基本上我有一个绑定到loginViewModel的loginView,在viewmodel中(使用命令绑定)我测试以查看登录是否成功,以及是否基本上加载了一个新View(主视图)并附加它的数据上下文...

Basically i have a loginView that is bound to a loginViewModel, in the viewmodel (using binding on a command) i test to see if the login is successful and if it is i basically load up a new View (mainview) and attach its datacontext...

但是我仍然显示了loginView-所以我需要发信号通知其卸载..

but i still have the loginView shown - so i need to signal it to unload..

我也希望有一个通用的解决方案,因为我确信在其他情况下我需要做这种事情

I was also hoping for a generic solution because i am sure that i am going to need to do this sort of thing in other situations

有什么想法吗?

推荐答案

参见

See my blog post for a more detailed explanation.

当需要实现此目标时,我使用创建的IRequestCloseViewModel接口.

When I need to achieve that, I use a IRequestCloseViewModel interface that I created.

此接口仅包含一个事件:RequestClose.当想要关闭其关联的视图时,ViewModel(继承自ViewModelBase类并实现IRequestCloseViewModel)会引发此事件.

This interface contains only one event: RequestClose. This event is raised by the ViewModel (which inherits from a ViewModelBase class AND implement IRequestCloseViewModel) when it wants to close its associated view.

在我的应用程序中,所有Window都从抽象类ApplicationWindow继承.每次DataContext更改时都会通知此抽象类,并且在处理程序中检查该DataContext是否支持IRequestCloseViewModel.在这种情况下,将设置事件处理程序以在触发事件时关闭窗口.

In my app, all Window inherit from an abstract class ApplicationWindow. This abstract class is notified each time the DataContext changed and in the handler checks if the DataContext support the IRequestCloseViewModel. If this is the case, an event handler is set up to close the Window when the event is fired.

或者,就像肯特(Kent)所说的那样,您可以使用屏幕控制器在外部类中处理这种机制.

Alternatively, like Kent said, you can use screen controller that handle this mecanism in an external class.

这篇关于WPF(MVVM):从Viewmodel关闭视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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