每个模型属性的C#复选框

| 我不确定是否可以通过简单的方式实现(只需编写少量代码即可)。 我有一个模型:
public static Class TestClass
{
    public static bool Test1 { get; set; }
    public static bool Test2 { get; set; }
    public static bool Test3 { get; set; }
    public static bool Test4 { get; set; }
    public static bool Test5 { get; set; }
    public static bool Test6 { get; set; }
}
一个简单的Foreach或其他命令能否创建6个复选框,每个复选框命名为属性名称并选中绑定到实际属性? 所以基本上我想为每个属性创建一个:
var check = new CheckBox { Name = Test1 };
check.CheckedChanged += (s,ea) => { TestClass.Test1 = check.IsChecked; }; 
但是对于每个属性,甚至可能用更少的代码?     
已邀请:
        有可能,但是我不知道您是否可以使用静态属性来做到这一点。
public class TestClass
{
    public bool Test1 { get; set; }
    public bool Test2 { get; set; }
    public bool Test3 { get; set; }
}

void Test(Control parent, TestClass tc)
{
    int y = 10;

    foreach (var prop in tc.GetType().GetProperties())
    {
        var cb = new CheckBox(); 
        cb.Name = prop.Name;   
        cb.Text = prop.Name;
        cb.DataBindings.Add(new Binding(\"Checked\", tc, prop.Name));
        cb.Location = new Point(10, y);
        parent.Controls.Add(cb);
        y += 25;
    }
}
例:
{
    var form = new Form();
    var tc = new TestClass();
    tc.Test2 = true;
    Test(form, tc);
    form.Show();
}
    
        也许以旧的方式:
public partial class Form1 : Form
{
    CheckBox[] cbs;
    public Form1()
    {
        InitializeComponent();
        cbs = new CheckBox[] { checkBox1, checkBox2 }; //put all in here
        for (int i = 0; i < cbs.Length; i++)
        {
            cbs[i].Name = \"myCheckBox\" + (i + 1);
            cbs[i].CheckedChanged += new EventHandler(CheckBoxes_CheckedChanged);
        }
    }

    private void CheckBoxes_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox cb = sender as CheckBox;
        MessageBox.Show(cb.Name + \" \" + ((cb.Checked) ? \" is checked\" : \"is not checked\").ToString());
    }

    private void buttonStateAll_Click(object sender, EventArgs e)
    {
        StringBuilder sb = new StringBuilder();
        foreach (CheckBox cb in cbs)
        {
            sb.AppendLine(cb.Name + \" \" + ((cb.Checked) ? \" is checked\" : \"is not checked\").ToString());
        }
        MessageBox.Show(sb.ToString());
    }
}
此代码将创建要在数组中包含的复选框的数组。然后,当您单击一个或有一个按钮时,它将向您显示消息,该按钮将为您提供所有复选框的实际状态。 希望对您有所帮助 再见     

要回复问题请先登录注册