多个按钮的事件如下: private void btnAdd_Click(object sender, EventArgs e) { MessageBox.Show("新增"); } private void btnModify_Click(object sender, EventArgs e) { MessageBox.Show("修改"); } private void btnDelete_Click(object sender, EventArgs e) { MessageBox.Show("删除"); } ...... 想动态对应绑定以上事件, pre class="brush: csharp"> var Items = new List<MyButton>() { new MyButton("新增","tbtnAdd","btnAdd_Click"), new MyButton("修改","tbtnModify","btnModify_Click"), new MyButton("删除","tbtnDelete","btnDelete_Click") }; foreach (var item in items) { var btn = new Button(); btn.Text = item.Text; btn.Name = item.Name; //btn.Click += new EventHandler(item.ClickEvent); //以上因为这句里的item.ClickEvent是字符串,知道事件的名称,怎样通过事件名称绑定事件 } 以下为自定义按钮对象: pre class="brush: csharp"> public class MyButton { public MyButton(string text, string name, string clickEvent) { Text = text; Name = name; ClickEvent = clickEvent; } public string Text { get; set; } public string Name { get; set; } public string ClickEvent { get; set; } } |
|
1分 |
只能返射来做了。
|
95分 |
var ei = typeof(Button).GetEvent("Click"); var d = Delegate.CreateDelegate(typeof(EventHandler), this, item.ClickEvent); ei.AddEventHandler(btn, d); /pre> |
2分 |
为什么不直接用EventHandler delegate呢?看不到用字符串的优点(字符串的好处是可以存数据库,但由于你用是函数名字,函数名字存储在外面,有泄露内部实现细节的嫌疑)。
pre class=”brush: csharp”> public class MyButton { public MyButton(string text, string name, EventHandler clickEvent) { Text = text; Name = name; ClickEvent = clickEvent; } public string Text { get; set; } public string Name { get; set; } public EventHandler ClickEvent { get; set; } } pre class=”brush: csharp”>var Items = new List<MyButton>() { new MyButton(“新增”,”tbtnAdd”,btnAdd_Click), new MyButton(“修改”,”tbtnModify”,btnModify_Click), new MyButton(“删除”,”tbtnDelete”,btnDelete_Click) }; foreach (var item in items) |
2分 |
都绑定同一个函数不好吗?
然后在函数里判断sender(触发事件的对象),强制转换回BUTTON,再根据不同的TEXT,show不同的内容 |