winform实现mvc架构完整示例代码
时间: 2023-09-02 17:03:18 浏览: 293
在WinForm中实现MVC架构的示例代码如下:
Model(模型):
```csharp
public class StudentModel
{
public string Name { get; set; }
public int Age { get; set; }
}
```
View(视图):
```csharp
public partial class StudentView : Form
{
private StudentController controller;
public StudentView(StudentController controller)
{
InitializeComponent();
this.controller = controller;
}
public void UpdateView(StudentModel student)
{
txtName.Text = student.Name;
txtAge.Text = student.Age.ToString();
}
private void btnSave_Click(object sender, EventArgs e)
{
string name = txtName.Text;
int age = int.Parse(txtAge.Text);
controller.UpdateStudent(name, age);
}
}
```
Controller(控制器):
```csharp
public class StudentController
{
private StudentModel model;
private StudentView view;
public StudentController(StudentModel model, StudentView view)
{
this.model = model;
this.view = view;
}
public void UpdateStudent(string name, int age)
{
model.Name = name;
model.Age = age;
view.UpdateView(model);
}
public void Initialize()
{
view.UpdateView(model);
}
}
```
程序入口:
```csharp
static void Main()
{
StudentModel model = new StudentModel();
StudentView view = new StudentView();
StudentController controller = new StudentController(model, view);
controller.Initialize();
Application.Run(view);
}
```
上述代码示例了一个简单的学生信息管理系统。Model(模型)定义了学生的属性,View(视图)是一个WinForm窗体用于展示学生信息,并提供一个保存按钮用于更新学生信息。Controller(控制器)用于处理用户交互和数据更新的逻辑。在程序入口处,我们创建了Model、View和Controller的实例,并通过Controller的初始化方法初始化视图,并启动应用程序运行。
注意:以上代码只是一个简单的示例,实际的MVC架构可能会涉及更多的模型、视图和控制器。
阅读全文