接着,我们定义View的接口ICustomerView。ICustomerView定义了两个事件,CustomerSelected在用户从Gird中选择了某个条客户记录是触发,而CustomerSaving则在用户完成编辑点击OK按钮视图提交修改时触发。ICustomerView还定义了View必须完成的三个基本操作:绑定客户列表(ListAllCustomers);显示单个客户信息到TextBox(DisplayCustomerInfo);保存后清空可编辑控件(Clear)。
复制代码 代码如下:
using System;
namespace MVPDemo
{
public interface ICustomerView : IViewBase
{
event EventHandler<CustomerEventArgs> CustomerSelected;
event EventHandler<CustomerEventArgs> CustomerSaving;
void ListAllCustomers(Customer[] customers);
void DisplayCustomerInfo(Customer customer);
void Clear();
}
}
事件参数的类型CustomerEventArgs定义如下,两个属性CustomerId和Customer分别代表客户ID和具体的客户,它们分别用于上面提到的CustomerSelected和CustomerSaving事件。
复制代码 代码如下:
using System;
namespace MVPDemo
{
public class CustomerEventArgs : EventArgs
{
public string CustomerId
{ get; set; }
public Customer Customer
{ get; set; }
}
}
而具体的Presenter定义在如下的CustomerPresenter类型中。在重写的OnViewSet方法中注册View的三个事件:Load事件中调用Model获取所有客户列表,并显示在View的Grid上;CustomerSelected事件中通过事件参数传递的客户ID调用Model获取相应的客户信息,显示在View的可编辑控件上;CustomerSaving则通过事件参数传递的被更新过的客户信息,调用Model提交更新。
复制代码 代码如下:
using System.Windows.Forms;
namespace MVPDemo
{
public class CustomerPresenter: Presenter<ICustomerView>
{
public CustomerModel Model
{ get; private set; }
public CustomerPresenter(ICustomerView view)
: base(view)
{
this.Model = new CustomerModel();
}
protected override void OnViewSet()
{
this.View.Load += (sender, args) =>
{
Customer[] customers = this.Model.GetAllCustomers();
this.View.ListAllCustomers(customers);
this.View.Clear();
};
this.View.CustomerSelected += (sender, args) =>
{
Customer customer = this.Model.GetCustomerById(args.CustomerId);
this.View.DisplayCustomerInfo(customer);
};
this.View.CustomerSaving += (sender, args) =>
{
this.Model.UpdateCustomer(args.Customer);
Customer[] customers = this.Model.GetAllCustomers();
this.View.ListAllCustomers(customers);
this.View.Clear();
MessageBox.Show("The customer has been successfully updated!", "Successfully Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
};
}
}
}