C# Checkbox per model property
I'm not sure if it is possible in a easy way (with little code that is).
I have a model:
public static Class TestClass
{
public static bool Te开发者_如何学JAVAst1 { 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; }
}
Is it possible for a simple Foreach or other command to create 6 checkboxes, each named as the property name and checked bound to the actual property?
So basicly what I want to create this for each property:
var check = new CheckBox { Name = Test1 };
check.CheckedChanged += (s,ea) => { TestClass.Test1 = check.IsChecked; };
but for each property and perhaps even with less code?
It's possible but I dont know if you can do it with static properties.
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;
}
}
example:
{
var form = new Form();
var tc = new TestClass();
tc.Test2 = true;
Test(form, tc);
form.Show();
}
Maybe in the old fashion way:
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());
}
}
This code will create an array of checkBoxes you want to have in array. Then it will show you message when ever you will click on one, or there is a button, which will give you the actual state of all checkBoxes. I hope its in a help, bye
精彩评论