MVVM基金会:如何从视图模型关闭应用程序窗口 [英] MVVM Foundation: How to close Application Window from ViewModel

查看:145
本文介绍了MVVM基金会:如何从视图模型关闭应用程序窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 MVVM基金会,但我认为它相当直接的,而不是真正的具体框架。我的设置如下:

I am using MVVM Foundation but I think its quite straight-forward and not really framework specific. My setup is as follows:


  • StartViewModel - 有一个返回RelayCommand / ICommand的一个ExitCommand

  • StartViewModel - has a ExitCommand that returns a RelayCommand/ICommand

public ICommand ExitCommand {
    get { return _exitCommand ?? (_exitCommand = new RelayCommand(() => MessageBox.Show("Hello World"))); }
}
public RelayCommand _exitCommand;


  • StartView(用户控制)具有绑定到ExitCommand一个按钮

  • StartView (User Control) has a button binded to the ExitCommand

    <Button Content="Exit" Command="{Binding ExitCommand}" />  
    


  • 推荐答案

    首先,阅读就像你可以在MVVM,例如胃 WPF应用程序与模型 - 视图 - 视图模型设计模式的MSDN上。一旦你理解了驾驶它的基本原则回答会显得更合理。

    First, read as much as you can stomach on MVVM, e.g. WPF Apps With The Model-View-ViewModel Design Pattern on MSDN. Once you understand the basic principles driving it the answer will seem more reasonable.

    基本上你要保持你的视图(UI)和视图模型(主要是抽象的用户界面,但也是抽象模型)层独立并脱钩。显示一个消息框或者关闭窗口应该算是UI具体细节,因此在View实现,或者在消息框中,更一般可通过一个'服务'的情况。

    Basically you want to keep your View (UI) and ViewModel (essentially abstract UI, but also abstract Model) layers separate and decoupled. Showing a message box or closing a window should be considered a UI specific detail and therefore implemented in the View, or in the case of a message box, more generally available via a 'Service'.

    对于视图模型,这是使用实现(IOC)的href=\"http://en.wikipedia.org/wiki/Inversion_of_control\" rel=\"nofollow\">反转。采取上述消息框的例子。而不是显示的信息框本身,它需要在其上有一个显示方法的IMessageBoxService的依赖和视图模型调用,而不是 - 委托责任。这可以进一步通过利用依赖注入(DI)容器服用。

    With respect to the ViewModel, this is achieved using Inversion of Control (IoC). Take the message box example above. Rather than showing the message box itself, it takes a dependency on an IMessageBoxService which has a Show method and the ViewModel calls that instead - delegating responsibility. This could be taken further by leveraging Dependency Injection (DI) containers.

    用于关闭视图窗口可能是视图模型公开事件,呼吁例如RequestClose(如MSDN文章),即查看订阅的另一种方法。然后,当它想对应的视图/窗口关闭视图模型将引发事件;它假定别的东西听,会负起责任,真正做到这一点。

    Another approach used for closing a View window might be for the ViewModel to expose an event, called for example RequestClose (as in the MSDN article), that the View subscribes to. Then the ViewModel would raise the event when it wants the corresponding View / window to close; it assumes something else is listening and will take responsibility and actually do it.

    这篇关于MVVM基金会:如何从视图模型关闭应用程序窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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