带有结构值的c#数据绑定

本文关键字:数据绑定 结构 | 更新日期: 2023-09-27 18:13:25

我需要一些关于我正在构建的驱动程序的帮助。我在静态类中有一些数据的结构。这个结构对象的数据必须从我的驱动程序类外部进行操作。在我的类中,我必须准备一些文本框,它们可以从类外分配和使用。每个结构值变成一个textBox。现在我的问题是,我必须连接这个动态可变结构值与相应的textBox。我必须使用数据绑定,因为我必须使用大量的数据。

请查看以下代码片段以了解:

    public static class driver
{
    #region " data preparation "
    //structure definition
    public struct _data
    {
        public string moduleName;
        public string dynamicNumber1;
        //...
    }
    //instance object of struct
    private _data moduleData = new _data();
    //get;set property
    public _data pModuleData
    {
        get
        {
            return moduleData;
        }
        set
        {
            moduleData = value;
        }
    }
    #endregion
    //build data binding(s) for each single "moduleData.structureItem"
    //???????????????????? moduleData_itemBinding_ModuleName
    //???????????????????? moduleData_itemBinding_dynamicNumber1
    //...
    #region " form elements preparation for external assignments "
    //instance of forms objects, data can be assigned and used outside of this public static class
    public static System.Windows.Forms.TextBox textBox_ModuleName = new System.Windows.Forms.TextBox();
    public static System.Windows.Forms.TextBox textBox_dynamicNumber1 = new System.Windows.Forms.TextBox();
    #endregion
            #region " class initialisation "
    static driver()
    {
            // class initialisation part   
        textBox_ModuleName.DataBindings = moduleData_itemBinding_ModuleName; //assign databindings from above ???????????
        textBox_ModuleName.DataBindings = moduleData_itemBinding_dynamicNumber1; //adding databindings from above ???????????
    }
    #endregion
}

谢谢你的帮助!

带有结构值的c#数据绑定

KISS.

我认为可以做到以下几点。定义你的类:

public class Driver
{
    public Driver(TextBox moduleName, TextBox dynamicNumber)
    {
        textBox_ModuleName = moduleName;
        textBox_DynamicNumber = dynamicNumber;
        textBox_ModuleName.DataBindings.Add("Text", this, "ModuleName");
        textBox_DynamicNumber.DataBindings.Add("Text", this, "DynamicNumber");
    }
    public string ModuleName { get; set; }
    public string DynamicNumber { get; set; }
    private TextBox textBox_ModuleName;
    private TextBox textBox_DynamicNumber;
}

然后在表单上创建文本框:

var textBox1 = new TextBox { Parent = this };
var textBox2 = new TextBox { Parent = this, Top = 30 };

创建你的类的实例并传递这些文本框给它:

var driver = new Driver(textBox1, textBox2);
driver.ModuleName = "foo";
driver.DynamicNumber = "bar";
// data will be appear in the textboxes