.net 使用 Windows 窗体实现 MVC

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/654722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:21:15  来源:igfitidea点击:

Implementing MVC with Windows Forms

.netwinformsmodel-view-controller

提问by kjv

Where can I find a good example on how to completely implement the MVC pattern in Windows Forms?

我在哪里可以找到关于如何在 Windows 窗体中完全实现 MVC 模式的好例子?

I found many tutorials and code examples on various sites (for example, The Code Projectand .NetHeaven), but many are more representative for the observer pattern than MVC. Since the application I want to develop is for a school project, I am reluctant to using frameworks like PureMVCor MVC#.

我在各种站点(例如,The Code Project和 .NetHeaven)上找到了许多教程和代码示例,但许多比 MVC 更能代表观察者模式。由于我要开发的应用程序是针对学校项目的,因此我不太愿意使用PureMVCMVC# 之类的框架。

回答by Ian Ringrose

I am of the view that applications are so different from each other and our understanding of how applications should be written is still very limited. Past Windows Forms applications I have worked on have been so different from each other. Some of the design differences I have seen are (including most combinations):

我认为应用程序彼此如此不同,我们对应用程序应该如何编写的理解仍然非常有限。我过去使用过的 Windows 窗体应用程序彼此如此不同。我看到的一些设计差异是(包括大多数组合):

  • Directly talk to the database (2 tier)
  • Use a backend that has been written for the given application (3 tier)
  • Use a set of web services that were written for use by many applications and can't be changed for your application. (Service-oriented architecture)
  • Updates being done by CRUDoperations
  • Updates being done with the command pattern(sending commands to backend server)
  • Lots of usages of data binding/ no usages of data binding
  • Most data being “table like” (e.g. invoices) that work well in standard grid controls / need custom controls for most of the UI data.
  • One developer / teams of 10 or 20 developers (just on the UI)
  • Lots of unit test using mocks etc / no unit tests
  • 直接与数据库对话(2层)
  • 使用为给定应用程序编写的后端(3 层)
  • 使用一组 Web 服务,这些服务是为许多应用程序使用而编写的,并且不能为您的应用程序更改。(面向服务的架构)
  • CRUD操作完成的更新
  • 使用命令模式进行更新(向后端服务器发送命令)
  • 大量使用数据绑定/不使用数据绑定
  • 大多数数据是“类似表格”(例如发票),在标准网格控件中运行良好/需要为大多数 UI 数据自定义控件。
  • 一名开发人员/由 10 或 20 名开发人员组成的团队(仅在 UI 上)
  • 使用模拟等进行大量单元测试/无单元测试

Therefore I don't think it's possible to create one implementation of MVC (or MVP) that always fits well.

因此,我认为不可能创建一种始终适合的 MVC(或 MVP)实现。

The best posts I have seen really explainingMVC and whyan MVC system is built the way it is, is the "Build Your Own CAB" series by Jeremy D Miller. After working though it you should be able to understand your options a lot better. Microsoft's Smart Client Guidance (CAB / Microsoft Composite Application Block)should also be considered. It is a bit complex, but it can work well for applications that have a good fit.

我见过的最好的帖子真正解释了MVC 以及为什么MVC 系统是这样构建的,是Jeremy D Miller“构建你自己的 CAB”系列。在工作之后,您应该能够更好地理解您的选择。 还应考虑Microsoft 的智能客户端指南(CAB/Microsoft Composite Application Block)。它有点复杂,但它可以很好地适用于非常适合的应用程序。

Selecting an MVC/MVP Implementation for a Winforms Projectgive an overview that is worth reading. A lot of people like PureMVC. I have never used it, but I would look at it the next time I need a MVC framework.

为 Winforms 项目选择MVC/MVP 实现提供了一个值得阅读的概述。很多人喜欢PureMVC。我从未使用过它,但下次我需要 MVC 框架时我会看看它。

"Presenter First" is a software development approach that combines the ideas of the Model View Presenter (MVP) design pattern and test-driven development. It lets you start off by writing tests in the customer's language. For example:

Presenter First”是一种软件开发方法,它结合了Model View Presenter (MVP) 设计模式和测试驱动开发的思想。它让您可以从用客户的语言编写测试开始。例如:

"When I click the 'save' button then the file should be saved and the unsaved file warning should disappear.”

“当我点击‘保存’按钮时,文件应该被保存,未保存的文件警告应该消失。”

I have no experience using "Presenter First," but I will give it a try when I get a chance, as it looks very promising.

我没有使用“Presenter First”的经验,但有机会我会尝试一下,因为它看起来很有前途。

Other Stack Overflow questions you may may wish to look at are hereand here.

您可能希望查看的其他堆栈溢出问题在这里这里

If you are thinking of using WPFat any point take a look at the Model-View ViewModel (MVVM)pattern. Here is a very good video you should take a look at: Jason Dolinger on Model-View-ViewModel.

如果您正在考虑在任何时候使用WPF,请查看模型视图视图模型 (MVVM)模式。这是一个非常好的视频,您应该看一看:Jason Dolinger on Model-View-ViewModel

MVVM (Model View View Model) Design Pattern for Winformsgive another option that may make it easer to convert to WPF if ever needed. Magical.Trevoris yet another MVVM sample for Windows Forms that also includes auto binding based on property names.

Winforms 的 MVVM(模型视图视图模型)设计模式提供了另一种选择,可以在需要时更轻松地转换为 WPF。 Magical.Trevor是 Windows 窗体的另一个 MVVM 示例,它还包括基于属性名称的自动绑定。



Also ask yourself whyyou are using MVC.

还要问问自己为什么要使用 MVC。

  • Do you wish to be able to unit test as much code as possible?
  • Are you trying to allow as much code as possible to be reused?
  • Are you trying to make your code base easy to understand?
  • 101 other reasons that can be valid for a given project.
  • 您是否希望能够对尽可能多的代码进行单元测试?
  • 您是否试图允许重用尽可能多的代码?
  • 您是否想让您的代码库易于理解?
  • 对给定项目有效的 101 个其他原因。

Once you are clear on your aims, it becomes easier to choose one implementation or another.

一旦您明确了自己的目标,就可以更轻松地选择一种或另一种实现方式。

回答by Igor Brejc

UPDATE: In addition to my previous answer below, I suggest reading about the "Presenter First" approach(especially the PDF articles)

更新:除了我之前在下面的回答之外,我建议阅读“演示者优先”方法(尤其是 PDF 文章)

I would recommend MVP (PassiveView pattern actually) instead of MVC. You don't really need any special frameworks for this, it's just how you organize your code.

我会推荐 MVP(实际上是 PassiveView 模式)而不是 MVC。你真的不需要任何特殊的框架,这只是你组织代码的方式。

One approach (which I usually take) is to split each windows form into three entities:

一种方法(我通常采用)是将每个窗体拆分为三个实体:

  1. A presenter/controller class - this is what you actually start with when developing a form. This is where most/all of your "business" logic should reside.
  2. A view interface (IView), which contains the methods, properties and events. This interface is allthat the presenter knows about your form.
  3. At the end, when you finish implementing the presenter and the view (including unit tests), you can then create the actual form class and make it implement the IView interface. Then it's just a question of adding appropriate controls to the form and wiring them to the interface.
  1. 演示者/控制器类 - 这是您在开发表单时实际开始的内容。这是您的大部分/所有“业务”逻辑应该驻留的地方。
  2. 一个视图接口 (IView),其中包含方法、属性和事件。此界面是演示者了解您的表单的全部内容。
  3. 最后,当您完成展示器和视图(包括单元测试)的实现时,您可以创建实际的表单类并使其实现 IView 接口。那么这只是将适当的控件添加到表单并将它们连接到界面的问题。

Example code (a simple pseudocode, just for illustration):

示例代码(一个简单的伪代码,仅用于说明):

interface IView
{
    string Username { get; set; }
    string Password { get; set; }

    event EventHandler LogOnButtonClicked;

    void InformUserLogOnFailed();
    void MoveToMainScreen();
}

class Presenter
{
    public Presenter(IView view)
    {
        this.view = view;
        view.LogOnButtonClicked += new EventHandler(OnLogOnButton);
    }

    private void OnLogOnButton()
    {
        // we ask some service to verify the username/password
        bool isLogOnOk = logOnService.IsUserAndPasswordOk(view.Username, view.Password);
        if (isLogOnOk)
            view.MoveToMainScreen();
        else
        {
            view.Username = "";
            view.Password = "";
            view.InformUserLogOnFailed();
        }
    }

    private IView view;
}

class Form : IView
{
    public Form()
    {
        presenter = new Presenter(this);
    }

    public string Username
    {
        get { return TextBoxUsername.Text; }
        set { TextBoxUsername.Text = value; }
    }

    public string Password
    {
        get { return TextBoxPassword.Text; }
        set { TextBoxPassword.Text = value; }
    }

    public void InformUserLogOnFailed()
    {
        MessageBox.Show("Invalid username or password.");
    }

    public void MoveToMainScreen()
    {
        // code for opening another form...
    }

    private Presenter presenter;
}

回答by Brian Lyttle

Have you looked at PureMVC? I've found that no one can agree on what MVC really looks like once they start building a specific implementation.

你看过PureMVC吗?我发现,一旦他们开始构建特定的实现,就没有人会就 MVC 的真正样子达成一致。

Update: You could build your own starting with something simpler such as MobileMVC. Compact Framework code should compile/run OK on Windows. Since this is a school assignment I would suggest that you actually spend some time learning how MVC actually works.

更新:您可以从更简单的东西开始构建自己的,例如MobileMVC。Compact Framework 代码应该可以在 Windows 上编译/运行正常。由于这是一项学校作业,我建议您实际上花一些时间学习 MVC 的实际工作原理。

回答by Mike Dunlavey

You might want to take a look at Differential Execution.

您可能想看看差异执行

Here it is in SourceForge

这是在SourceForge 中

IMO, it is a vast improvement on MVC, though it is still quite unusual.

IMO,这是对 MVC 的巨大改进,尽管它仍然很不寻常。

回答by Gary.Ray

A good example at rolling your own implementation of MVC using Windows Forms can be found here. Source code is included.

可以在此处找到使用 Windows 窗体滚动您自己的 MVC 实现的一个很好的示例。包含源代码。

As you read, study, and write code for this assignment you are going to find that there are a lot of disagreements on how MVC should be implemented. This one is a simple case that reflects the separation of concerns as well as a good example of the 'plumbing' required to hook this up.

当您阅读、学习和编写此作业的代码时,您会发现对于 MVC 应该如何实现存在很多分歧。这是一个简单的案例,反映了关注点的分离以及将其连接起来所需的“管道”的一个很好的例子。

When you are out of school you will probably want to fall back on a framework like the other posters have recommended.

当你离开学校时,你可能想要回到其他海报推荐的框架上。

回答by Rui Craveiro

Microsoft Composite Interface Application block started its life as a MVC implementation (amongst other patterns it implemented). The release version, however, evolved into an MVP implementation, which can be argued to be a kind of a different interpretation of the MVC concept.

Microsoft 复合接口应用程序块作为 MVC 实现(在它实现的其他模式中)开始了它的生命。然而,发布版本演变成 MVP 实现,这可以说是对 MVC 概念的一种不同解释。

If you are willing to check the code of a very complete (and somehow complex) MVP implementation, you can find the MS-CAB as one of the components of Microsoft Smart Client Software Factory. It comes with source code. You can find it here. Good luck!

如果您愿意检查一个非常完整(并且有些复杂)的 MVP 实现的代码,您可以发现 MS-CAB 作为 Microsoft 智能客户端软件工厂的组件之一。它带有源代码。你可以在这里找到它。祝你好运!