Data binding 动态绑定DataRepeater(Microsoft.VisualBasic.PowerPacks)

Data binding 动态绑定DataRepeater(Microsoft.VisualBasic.PowerPacks),data-binding,winforms,datarepeater,powerpacks,Data Binding,Winforms,Datarepeater,Powerpacks,我使用DataRepeater在屏幕上显示来自业务对象的数据。我正在使用C语言中的windows窗体来完成这项工作。数据源在编译时不可用,所以我想在运行时绑定数据源 下面是简化的场景。我正在使用这个商务舱: public class Product { private double _price; public double Price { get { return _price; }

我使用DataRepeater在屏幕上显示来自业务对象的数据。我正在使用C语言中的windows窗体来完成这项工作。数据源在编译时不可用,所以我想在运行时绑定数据源

下面是简化的场景。我正在使用这个商务舱:

public class Product
{

    private double _price;
    public double Price 
    { 
        get
        {
            return _price;
        }
        set
        {
            _price = value;
        }
    }
}
我已经创建了一个带有VisualStudio界面的ProductDataSource,并将价格绑定到标签上。现在,我用代码填充了中继器的数据源:

dataRepeater1.DataSource = _productDataAgent.GetProducts();
当我启动我的应用程序的价格是正确填写在标签上。到目前为止还不错

现在我想在产品更新时更新价格标签。VisualStudio界面帮助我,让我选择“数据源更新模式”。所以我选择了OnPropertyChanged

棘手的部分来了。NET运行时如何知道price属性是从后端更新的。因此,我修改了我的业务类以实现INotifyPropertyChanged。像这样:

public class Product : INotifyPropertyChanged
{
    private double _price;

    public double Price 
    { 
        get
        {
            return _price;
        }
        set
        {
            _price = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Price"));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}
问题是这不起作用。当我更新产品时,它会在界面中显示为未更新。调试和更改属性时,我看到PropertyChanged事件为null,因此没有人在侦听

深入研究这个问题,我在MSDN的System.Windows.Forms.Binding构造函数页面上发现了以下内容:

名为PropertyNameChanged的事件

所以我尝试使用一个定制的PriceChanged事件,但没有成功


我做错什么了吗?我是从使用WPF开始的,所以这在Windows窗体中可能会有点不同?这是因为我在运行时绑定吗?

Jep找到了解决方案。显然,您不能简单地绑定到产品列表。最初您将看到这些产品,但当属性更改时,这些产品将不会更新。相反,您需要静态绑定到BindingSource。只需使用“数据”菜单中的Visual Studio创建一个对象数据源。生成如下代码:

private System.Windows.Forms.BindingSource beursProductDisplayBindingSource;
this.beursProductDisplayBindingSource = new System.Windows.Forms.BindingSource(this.components);
this.dataRepeater1.DataSource = this.beursProductDisplayBindingSource;
现在您可以这样动态绑定:

BindingSource productBinding = ((BindingSource)dataRepeater1.DataSource);
_productDataAgent.BeursProducts.ForEach(product => productBinding.Add(product));
现在,在数据对象中实现INotifyPropertyChanged时,就像我所做的一样,它的工作与预期的一样。只是忘记了使用WPF时不需要的一个步骤