0

我正在使用 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 Constructor 页面上发现了以下内容:

名为 PropertyNameChanged 的​​事件。

所以我尝试使用(自定义)PriceChanged 事件,但这不起作用。

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

4

1 回答 1

0

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

于 2009-10-12T21:27:40.380 回答