【问题标题】:What am I doing wrong in binding to a class?我在绑定课程时做错了什么?
【发布时间】:2012-05-15 20:05:37
【问题描述】:

我有一个名为 PlatypusInfo 的类。

我调用了一个返回该类实例的方法:

PlatypusInfo pi;
. . .
pi = MammalData.PopulateplatypusData(oracleConnectionMainForm, textBoxPlatypusID.Text);
. . .
public static PlatypusInfo PopulateplatypusData(OracleConnection oc, String platypusID) {

    int platypusABCID = getABCIDForDuckBillID(oc, platypusID);
    platypusInfo pi = new platypusInfo();

...但是得到这个错误消息:"System.ArgumentException 未处理 Message=无法绑定到 DataSource 上的属性或列 platypusName。 参数名称:dataMember 源=System.Windows.Forms ParamName=dataMember"

...在这行代码上:

textBoxPlatypusID.DataBindings.Add(new Binding("Text", pi, "platypusName"));

我在想,通过我的代码,PlatypusInfo 类的 platypusName 成员(其实例是“pi”)应该分配给 textBoxPlatypusID 的 Text 属性。

那么我是不是理解错了,是我做错了,还是两者兼而有之?

【问题讨论】:

  • 类 PlatypusInfo 是否有一个名为 'platypusName' 的字符串类型的公共属性?
  • 你能把PlatypusInfo的代码贴出来
  • @John:不完全是一个属性:public class PlatypusInfo { public String PlatypusName;
  • @John:我不知道你的字面意思是“财产”
  • @ClayShannon:将其更改为属性,并确保大小写匹配。

标签: c# winforms data-binding


【解决方案1】:

您需要将其从字段更改为属性并添加INotifyPropertyChanged 接口的实现。所以是这样的:

public class PlatypusInfo : INotifyPropertyChanged
{         
    public event PropertyChangedEventHandler PropertyChanged;
    private String _PlatypusName;

    public String PlatypusName 
    { 
       get
       {
          return _PlatypusName;
       }
       set 
       {
          _PlatypusName = value;
          NotifyPropertyChanged("PlatypusName");
       }
    }

    private void NotifyPropertyChanged(String info)
    {
       PropertyChangedEventHandler property_changed = PropertyChanged;
       if (property_changed != null)
       {
          property_changed(this, new PropertyChangedEventArgs(info));
       }
    }
}

那么数据绑定将如下所示:

textBoxPlatypusID.DataBindings.Add(new Binding("Text", pi, "PlatypusName"));

假设 pi 是一个 PlatypusInfo 对象。

【讨论】:

    【解决方案2】:

    类 PlatypusInfo 是否实现了接口 INotifyPropertyChanged

    【讨论】:

    • 当你使用数据绑定时你必须实现INotifyPropertyChanged,而对于集合你需要使用ObservableCollection
    • 如果您希望您的 UI 在支持数据更改时更新,您只需实现这些接口。无论如何绑定都会起作用。
    猜你喜欢
    • 2020-08-30
    • 1970-01-01
    • 2010-10-27
    • 2011-05-08
    • 1970-01-01
    • 1970-01-01
    • 2023-03-08
    • 2011-08-07
    • 2017-09-29
    相关资源
    最近更新 更多