我不确定这是否有可能以简单的方式进行(代码很少)。
我有一个模特:
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; };
但对于每个属性,甚至可能用更少的代码?
答案 0 :(得分:3)
这是可能的,但我不知道你是否可以使用静态属性。
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();
}
答案 1 :(得分:1)
也许以旧时尚的方式:
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());
}
}
此代码将创建一个您希望在数组中拥有的复选框数组。然后它将显示您何时单击一个消息,或者有一个按钮,它将为您提供所有复选框的实际状态。 我希望它能得到帮助, 再见