如何在Winform应用程序中将视图与逻辑分开?


18

我知道有像MVC这样的模式可以将视图与逻辑分开,但是,我不知道它们在Winform应用程序中有多常见。

对于C#Winform应用程序,我可以从开始Form并逐步向其中添加UI组件,然后针对组件的事件(clicktextchanged...),我调用函数,或直接在其中编写逻辑!

我知道这是一个坏习惯,但是我不知道在Visual Studio中启动此类项目的最佳方法是什么(模板,框架,起点),MVC是唯一的解决方案吗?我应该为任何项目这样做吗?

我希望获得一些入门指南或轻量级框架。


2
这是您正在寻找的完整教程:codebetter.com/jeremymiller/2007/07/26/…–
布朗

Answers:


25

MVVM(Model-View-ViewModel)模式可用于 Winforms

模型

public class Person
{
    public string FirstName {get; set;}
    public string LastName {get; set;}
}

视图模型

public class PersonViewModel : INotifyPropertyChanged
{
    private Person _Model;

    public string FirstName
    {
        get { return _Model.FirstName; }
        set(string value)
        {
            _Model.FirstName = value;
            this.NotifyPropertyChanged("FirstName");
            this.NotifyPropertyChanged("FullName"); //Inform View about value changed
        }
    }

    public string LastName
    {
        get { return _Model.LastName; }
        set(string value)
        {
            _Model.LastName = value;
            this.NotifyPropertyChanged("LastName");
            this.NotifyPropertyChanged("FullName");
        }
    }

    //ViewModel can contain property which serves view
    //For example: FullName not necessary in the Model  
    public String FullName
    {
        get { return _Model.FirstName + " " +  _Model.LastName; }
    }

    //Implementing INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
}

视图

public class PersonView: Form
{
    //Add two textbox and one label to the form
    //Add BindingSource control which will handle 
    //ViewModel and Views controls changes


    //As viewmodel you can use any type which of course have same named properties
    public PersonView(Object viewmodel)
    {
        this.InitializeComponents();

        this.ViewModelBindingSource.DataSource = viewmodel;
        this.InitializeDataBindings();
    }

    private void InitializeDataBindings()
    {
        this.TextBoxFirstName.DataBindings.Add("Text", this.ViewModelBindingSource, "FirstName", true);
        this.TextBoxLastName.DataBindings.Add("Text", this.ViewModelBindingSource, "LastName", true);
        this.LabelFullName.DataBindings.Add("Text", this.ViewModelBindingSource, "FullName", true);
    }
}

从MSDN阅读有关Winforms中数据绑定的更多信息


0

显然,WinForms本机不支持另一种设计模式-MVVM可能无法使用,因为您无法将数据“绑定”到视图模型并直接更新数据。

否则-我将尝试使用MVP进行WinForms-我之前已经看过-这是查看https://winformsmvp.codeplex.com/的链接

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.