And*_*ens 7 data-binding mvp winforms
我主要来自ASP.Net背景和一些MVC.我还做了一点Silverlight和MVVM,但是我现在要进入Winforms,我很少有经验,所以我想知道如何解决MVP问题.
典型的MVP示例显示了演示者设置视图属性(通过某种IView接口),具体视图将该属性值放入文本框中.而不是这种古老的方法,可以在MVP中使用INotifyPropertyChanged,如果是,如何?一个非常快速的例子非常有用!
如果我要创建一个实现INotifyPropertyChanged的模型,那么这不是更像MVVM吗?(即演示者更新模型,并通过INotifyPropertyChanged的魔力更新视图).然而,在我读过有关MVVM和Winforms的各个地方,人们都认为它不合适.为什么?我的理解是你可以对任何控件的属性进行数据绑定,那么Winforms缺少什么?我试图理解Winforms中数据绑定与WPF相比的缺点,以及为什么不能使用MVVM,因为它似乎比MVP更容易实现.
在此先感谢安迪.
我刚刚检查了WinForms中的数据绑定如何使用INotifyPropertyChanged.该数据通过绑定的BindingSource并真正支持INotifyPropertyChanged的,如果数据源中的对象的BindingSource对应或模型属性数据成员实现了这一点.你可以在这里完全使用M. Fowlers监督演示者/控制器:你甚至不需要手写代码,BindingSource将视图与两个方向的模型属性同步(模型 - >视图和视图 - >模型) ,如果模型支持INotifyPropertyChanged,则视图将自动更新.到目前为止我使用的代码构造:
视图初始化期间:
this.bindingSource.DataSource = this.presenter;
Designer生成的代码:
this.textBoxPhone.DataBindings.Add(new System.Windows.Forms.Binding("Text",this.bindingSource,"Model.Phone",true,System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));
模型类:
public class Customer : INotifyPropertyChanged
{
private string _firstName;
public string FirstName
{
get { return _firstName; }
set
{
if (_firstName == value)
return;
_firstName = value;
NotifyPropertyChanged("FirstName");
}
}
private string _lastName;
public string LastName
{
get { return _lastName; }
set
{
if (_lastName == value)
return;
_lastName = value;
NotifyPropertyChanged("LastName");
}
}
private string _company;
public string Company
{
get { return _company; }
set
{
if (_company == value)
return;
_company = value;
NotifyPropertyChanged("Company");
}
}
private string _phone;
public string Phone
{
get { return _phone; }
set
{
if (_phone == value)
return;
_phone = value;
NotifyPropertyChanged("Phone");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Run Code Online (Sandbox Code Playgroud)
演示者课程:
public class CustomerPresenter
{
public CustomerPresenter(Customer model)
{
if (model == null)
throw new ArgumentNullException("model");
this.Model = model;
}
public Customer Model { get; set; }
public ICustomerView View { private get; set; }
}
Run Code Online (Sandbox Code Playgroud)