如何为许多标签编写通用的ClickEvent? [英] How to write a common ClickEvent for many labels?
本文介绍了如何为许多标签编写通用的ClickEvent?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在面板上有10个标签-和10个相同的ClickEvent(更改BackColor)。
如何减少代码,即编写通用过程?
类似:
I have 10 labels on a panel - and 10 identical ClickEvents (change BackColor).
How could I reduce the code, i.e. write a common procedure ?
Something like:
foreach (Control c in panelA.Controls)
if (c.Tag == "abc" && c.is clicked)
c.BackColor = Color.Crimson;
推荐答案
遍历标签并将处理程序连接到Click事件:
Iterate over labels and wire a handler to Click event:
foreach (Control c in panelA.Controls)
{
c.Click += HandleClick;
}
然后,在点击处理程序中,您可以使用发件人
参数,将包含在其上进行点击的标签:
Then, in the click handler, you can change the background color by using the sender
parameter that will contain the label the click was made on:
private void HandleClick(object sender, EventArgs e)
{
((Control)sender).BackColor = Color.Crimson;
}
这篇关于如何为许多标签编写通用的ClickEvent?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文