gpt4 book ai didi

c# - Winforms 数据绑定(bind) : Period-delimited navigation path as DataMember causes exception. 为什么?

转载 作者:行者123 更新时间:2023-11-30 18:41:17 25 4
gpt4 key购买 nike

我一直遇到 Winforms 数据绑定(bind)问题,更具体地说,每当我指定一个句点分隔的属性路径用作 DataMember 时。例如:

public partial class SomeForm : System.Windows.Forms.Form
{
public SomeForm(Book bookToBeDisplayed)
{
InitializeComponent();

authorLabel.DataBindings.Add("Text", bookToBeDisplayed, "Author.Name");
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// I cannot get this to work.
}
}


public class Book : INotifyPropertyChanged
{
public Person Author { … }

}

public class Person : INotifyPropertyChanged
{
public string Name { … }

}

我在 authorLabel.TextbookToBeDisplayed.Author.Name 之间添加绑定(bind)的行抛出以下异常:

ArgumentException: Cannot bind to the property or column Name on the DataSource.

MSDN page about System.Windows.Forms.Binding 的“备注”部分解释了句点分隔的导航路径可以用作 DataMember:

You can also use a period-delimited navigation path when you bind to an object whose properties return references to other objects (such as a class with properties that return other class objects).

我需要做什么才能让上面的例子起作用?

  • 我已经确保传递给 SomeForm 的构造函数的 Book 实例已正确初始化,并且没有 null引用。
  • 我也不想求助于 DataSets

最佳答案

我找到了一个解决方案。显然,DataSource不能是单个对象,而是集合:

authorLabel.DataBindings.Add("Text",
new Book[] { bookToBeDisplayed }, // <--
"Author.Name");

the MSDN page "Data Binding and Windows Forms" 的“数据绑定(bind)类型”部分提到有两种类型的数据绑定(bind):“简单”和“复杂”。后一种绑定(bind)类型也称为“基于列表的绑定(bind)”。似乎只有后一种绑定(bind)类型才支持导航路径。

附注:MSDN 还建议使用 BindingList<T> ,尽管这里可能没有必要。

关于c# - Winforms 数据绑定(bind) : Period-delimited navigation path as DataMember causes exception. 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6987850/

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