gpt4 book ai didi

winforms - Winforms MVP

转载 作者:行者123 更新时间:2023-12-03 05:19:22 29 4
gpt4 key购买 nike

我主要具有 ASP.Net 背景,并具有一些 MVC 知识。我也做了一些 Silverlight 和 MVVM,但是我现在即将转向 Winforms,我对它的经验很少,所以我想知道如何处理 MVP。

典型的 MVP 示例显示演示者设置 View 属性(通过某种 IView 接口(interface)),例如具体 View 将该属性值放入文本框中。可以在 MVP 中使用 INotifyPropertyChanged 来代替这种过时的方法吗?如果可以的话,如何使用?一个非常简单的例子将非常有用!

如果我要创建一个实现 INotifyPropertyChanged 的​​模型,那么这不是更像 MVVM 吗? (即演示者更新模型,并通过 INotifyPropertyChanged 的​​魔力更新 View )。然而,我在任何地方读到有关 MVVM 和 Winforms 的内容,人们都说它不合适。为什么?我的理解是,您可以对任何控件的属性进行数据绑定(bind),那么 Winforms 缺少什么?我试图了解与 WPF 相比 Winforms 中的数据绑定(bind)的缺点,以及为什么不能使用 MVVM,因为它似乎比 MVP 更容易实现。

提前致谢安迪。

最佳答案

我刚刚检查了 WinForms 中的数据绑定(bind)如何使用 INotifyPropertyChanged。如果 BindingSourceDataSource 对象或模型属性对应于DataMember 实现了这一点。您可以在这里充分利用 M. Fowlers 监督演示者/控制者:您甚至不需要手写代码,BindingSource 会在两个方向(模型 -> View 和 View -> 模型)同步 View 与模型属性,并且如果模型支持INotifyPropertyChanged 然后 View 将自动更新。到目前为止我使用过的代码结构:

  1. 在 View 初始化期间:

    this.bindingSource.DataSource = this.presenter;

  2. 设计者生成的代码:

    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));
}
}

演示者类:

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; }
}

关于winforms - Winforms MVP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9301848/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com