gpt4 book ai didi

c# - Visual Studio 中的基本 Winforms 数据绑定(bind)(设计器模式)

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

我似乎无法让基本的数据绑定(bind)在 WinForms 设计器中工作。 (使用 VS2012)

  1. 我创建了一个名为 DatabindTest 的新 Win Forms 应用程序项目。
  2. 我向这个项目添加了一个名为 Class1.cs 的类。
  3. 在这个类中,我创建了一个名为 MyProperty 的 (String) 属性以及一个将 MyProperty 设置为“abc”的构造函数。
  4. 我构建解决方案。
  5. 使用 Form1 设计器,我将文本框添加到表单 (textBox1)。
  6. textBox1 的属性中,展开 DataBindings 并打开“高级”对话框。 enter image description here
  7. 我展开绑定(bind)下拉菜单,点击添加项目数据源...,然后选择对象数据源。然后我展开 DatabindTest 节点并选择 Class1 作为数据对象。 enter image description here
  8. 我确认 Binding 字段现在显示“class1BindingSource - MyProperty”(如预期)。
  9. Form1.csForm1 类的开头,我创建了 Class1 的新实例(请参见下面的代码)。
  10. 此时,我构建并启动了程序。我希望在文本框中看到“abc”,但它是空的。

我做错了什么?

public partial class Form1 : Form
{
Class1 c1 = new Class1();
public Form1()
{
InitializeComponent();
//this.textBox1.Text = c1.MyProperty; //if I uncomment this line,
//"abc" appears in textBox1
//so why not through databinding?
}
}

最佳答案

您应该设置 class1BindingSourceDataSource:

class1BindingSource.ِDataSource = c1;

如果您查看设计器为您的文本框和数据绑定(bind)生成的代码,您将看到如下代码:

this.textBox1.DataBindings.Add(new System.Windows.Forms.Binding("Text",
this.class1BindingSource, "MyProperty", true));

如您所见,class1BindingSource 是数据绑定(bind)的数据源,您应该将数据传递给它的DataSource 以在Text 中显示> textBox1 的属性。

关于c# - Visual Studio 中的基本 Winforms 数据绑定(bind)(设计器模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38064356/

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