Demo mô hình MVP trong Windows Forms
Student Model:
public class Student { public string FirstName { get; set; } public string LastName { get; set; } public string IdentityCardNumber { get; set; } } Interface Add New Student
public interface IAddStudent { string FirstName { get; set; } string LastName { get; set; } string IdentityCardNumber { get; set; } string Message { get; set; } } View Add New Student:
Code Behind:
public partial class AddStudent : Form, IAddStudent
{
public AddStudent()
{
InitializeComponent();
}
public string FirstName
{
get
{
return txtFirstName.Text;
}
set
{
txtFirstName.Text = value;
}
}
public string LastName
{
get
{
return txtLastName.Text;
}
set
{
txtLastName.Text = value;
}
}
public string IdentityCardNumber
{
get
{
return txtIdentityCardNumber.Text;
}
set
{
txtIdentityCardNumber.Text = value;
}
}
private string _message;
public string Message
{
get
{
return _message;
}
set
{
_message = value;
MessageBox.Show(_message);
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
StudentPresenter pre = new StudentPresenter(this);
pre.AddStudent();
}
}
Student Presenter
class StudentPresenter { IAddStudent addStudentView; public StudentPresenter(IAddStudent addStudentView) { this.addStudentView = addStudentView; } public bool AddStudent() { Student student = new Student(); student.FirstName = addStudentView.FirstName; student.LastName = addStudentView.LastName; student.IdentityCardNumber = addStudentView.IdentityCardNumber; addStudentView.Message = string.Format("Thêm má»›i thành công sinh viên: {0} {1}", student.FirstName, student.LastName); //insert into db return true; } }
Test thử: