使用c#/ WinForms将数据绑定到重复用户控件中的控件 [英] Binding data to controls in a Repeating user control with c#/WinForms

查看:193
本文介绍了使用c#/ WinForms将数据绑定到重复用户控件中的控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WinForms UI,我们有一个需要动态添加重复控件的要求。
我设法创建了一个带有所有标签和文本框的UserControl,并像这样添加它们:

I am working on WinForms UI and we have a requirement where we need to add repeating controls dynamically. I managed to create a UserControl with all labels and text boxes and adding them like this:

for (int i= 0; i < 4;i ++) {
    tableLayoutPanel1.Controls.Add(new MyUserControl(),1,1);      
    //1,1 represent 1st row, 1st column of tablelayoutpanel 
} 

现在我无法找到将不同数据绑定到每个控件的方法。例如:每次添加新的用户控件时,我需要在每个文本框中显示不同的联系信息。但是由于其相同的UserControl,文本框和标签具有相同的名称,我不确定如何使用相同的UserControl绑定不同的数据。

Now I am not able to find a way to bind different data to each control. For example: I need to display different contact information in each textbox every time a new user control is added. But since its the same UserControl, the textbox and labels have the same name and i am not sure how to bind different data using same UserControl.

我需要这样的东西:我能够反复添加控件,但不能绑定数据:
截图

I need something like this: I am able to add controls repeatedly, but not able to bind data: Screenshot

任何帮助将不胜感激。

推荐答案

如果要创建自定义用户控件。您可以为喜欢的人提供数据绑定功能。您可以在构造函数中使用参数来传递数据:

If you are creating custom user-controls. You can provide data-binding capabilities for your likes. You could use a parameter in the constructor to pass data in:

public MyUserControl(MyData mydata):this()
{ ...
}

您可以提供属性,以设置所需的数据稍后:

You can provide a property, to set the required data later:

public class MyUserControl()
{ 
   ...
   public MyData MyDataSource {get;set;}
}

您冷传递了一个收集数据的函数:

You cold pass in a function to collect data:

 public MyUserControl(func<MyData> mydata):this()
 { 

 }

或某种服务来检索数据:

Or some sort of service to retrieve the data:

 public MyUserControl(IMyService myService):this()
 {
    Textbox1.Text = myService.GetImportantText();
 }

如果MyData实现INotifyPropertyChanged(或任何自定义事件),您将能够做出反应数据更改并显示它们。
我想您知道需要创建多少个控件。如果是,您也知道为什么以及需要提供哪些数据。

If MyData implements INotifyPropertyChanged (or any custom event), you will be able react to data changes and display them. I guess you know how many controls need to be created. If yes, you know also why and which data you need provide.

这篇关于使用c#/ WinForms将数据绑定到重复用户控件中的控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆