您将如何在Windows Forms应用程序中实现MVC? [英] How would you implement MVC in a Windows Forms application?

查看:79
本文介绍了您将如何在Windows Forms应用程序中实现MVC?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有开发太多的台式机/Windows Forms应用程序,但是我想到使用MVC(模型视图控制器)模式进行Windows Forms .NET开发可能会有一些好处.

I don't develop too many desktop / Windows Forms applications, but it had occurred to me that there may be some benefit to using the MVC (Model View Controller) pattern for Windows Forms .NET development.

有人在Windows窗体中实现MVC吗?如果是这样,您对设计有什么建议吗?

Has anyone implemented MVC in Windows Forms? If so, do you have any tips on the design?

推荐答案

我过去所做的是使用类似的方法,

What I've done in the past is use something similar, Model-View-Presenter.

[注意:这篇文章以前可以在网上获得.要立即查看,您需要下载CHM,然后查看文件属性并单击取消阻止".然后,您可以打开CHM并找到该文章.谢谢百万,微软! 叹气]

[NOTE: This article used to be available on the web. To see it now, you'll need to download the CHM, and then view the file properties and click Unblock. Then you can open the CHM and find the article. Thanks a million, Microsoft! sigh]

窗体是视图,我有一个IView接口.所有处理都在演示者中进行,这只是一个类.该表单将创建一个新的演示者,并将自身作为演示者的IView传递.通过这种测试方式,您可以传递一个伪造的IView,然后从演示者向其发送命令并检测结果.

The form is the view, and I have an IView interface for it. All the processing happens in the presenter, which is just a class. The form creates a new presenter, and passes itself as the presenter's IView. This way for testing you can pass in a fake IView instead, and then send commands to it from the presenter and detect the results.

如果我要使用成熟的Model-View-Controller,我想我会这样做:

If I were to use a full-fledged Model-View-Controller, I guess I'd do it this way:

  • 该表单是视图.它向模型发送命令,引发控制器可以订阅的事件,并订阅来自模型的事件.
  • 控制器是一个类,用于订阅视图的事件并向视图和模型发送命令.
  • 模型引发视图订阅的事件.
  • The form is the view. It sends commands to the model, raises events which the controller can subscribe to, and subscribes to events from the model.
  • The controller is a class that subscribes to the view's events and sends commands to the view and to the model.
  • The model raises events that the view subscribes to.

这符合经典MVC图.最大的缺点是,通过事件,可能很难分辨出谁在订阅什么. MVP模式使用方法而不是事件(至少是我实现它的方式).当表单/视图引发事件(例如someButton.Click)时,表单仅在演示者上调用一个方法来为其运行逻辑.视图和模型根本没有任何直接联系;他们俩都必须经过主持人.

This would fit with the classic MVC diagram. The biggest disadvantage is that with events, it can be hard to tell who's subscribing to what. The MVP pattern uses methods instead of events (at least the way I've implemented it). When the form/view raises an event (e.g. someButton.Click), the form simply calls a method on the presenter to run the logic for it. The view and model don't have any direct connection at all; they both have to go through the presenter.

这篇关于您将如何在Windows Forms应用程序中实现MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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