一、动态绑定右键菜单控件
/// <summary>
/// 通过递归获取执行控件
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="c"></param>
/// <param name="acction"></param>
private void actionSetContextMenuStrip<T>(Control c, Action<T> acction) where T : Control
{
if (c is T)
{
if (acction != null)
{
acction((T)c);
}
}
else
{
foreach (Control item in c.Controls)
{
actionSetContextMenuStrip<T>(item, acction);
}
}
}
二、调用
System.Windows.Forms.ContextMenuStrip cms2 = new System.Windows.Forms.ContextMenuStrip();
ToolStripMenuItem tsmiShowFixedValue = new ToolStripMenuItem() { Text = "查看默认标识的元素" };
tsmiShowFixedValue.BackColor = PublicColor.MyColorTeeL;
Action<Object, EventArgs> actionShowFixedValue = (o, e) =>
{
actionShowClear(o, e);
};
tsmiShowFixedValue.Click += new EventHandler(actionShowFixedValue);
cms2.Items.Add(tsmiShowFixedValue);
//绑定右键菜单
actionSetContextMenuStrip<Panel>(this.panelOperate, (c) =>
{
c.ContextMenuStrip = cms2;
});