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

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

问题描述

我没有开发太多桌面/Windows 窗体应用程序,但我突然想到使用 MVC(模型视图控制器)模式进行 Windows 窗体 .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 接口.所有的处理都发生在 Presenter 中,它只是一个类.表单创建一个新的演示者,并将自身作为演示者的 IView 传递.通过这种测试方式,您可以传入一个假的 IView,然后从 Presenter 向它发送命令并检测结果.

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.

如果我要使用成熟的模型-视图-控制器,我想我会这样做:

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 窗体应用程序中实现 MVC?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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