【问题标题】:Dynamically bind a DataRepeater (Microsoft.VisualBasic.PowerPacks)动态绑定 DataRepeater (Microsoft.VisualBasic.PowerPacks)
【发布时间】:2009-10-09 21:16:44
【问题描述】:

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

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

public class Product
{

    private double _price;
    public double Price 
    { 
        get
        {
            return _price;
        }
        set
        {
            _price = value;
        }
    }
}

我使用 VisualStudio 界面创建了一个 ProductDataSource 并将价格绑定到一个标签。现在我用代码填充了中继器的数据源:

dataRepeater1.DataSource = _productDataAgent.GetProducts();

当我启动我的应用程序时,价格已正确填写在标签中。到目前为止,一切都很好。

现在我希望在产品更新时更新价格标签。 Visual Studio 界面帮助我,让我选择“数据源更新模式”。所以我选择“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 事件为空,所以没有人在监听。

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

名为 PropertyNameChanged 的​​事件。

所以我尝试使用(自定义)PriceChanged 事件,但没有奏效。

我在这里做错了吗?我来自使用 WPF,所以这在 Windows 窗体中可能有点不同?这是因为我是在运行时绑定的吗?

【问题讨论】:

    标签: data-binding winforms datarepeater powerpacks


    【解决方案1】:

    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 时不需要的一个步骤。

    【讨论】:

      猜你喜欢
      • 2010-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 2011-08-28
      • 2023-04-01
      相关资源
      最近更新 更多