我正在撰写自定义ToolStripProfessionalRenderer
例如,以下覆盖:
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if(e.ToolStrip is MenuStrip)
{
// It never is. It's always ToolStripDropDownMenu
}
}
我想下拉菜单会调用OnRenderImageMargin
,因为这是要呈现的内容,但我希望得到父ToolStrip
/ MenuStrip
/ StatusStrip
导致OnRenderImageMargin
调用。
这可能吗?
答案 0 :(得分:1)
我认为e.ToolStrip.Parent
属性是关键,但它总是null
。
一种选择是在ToolStripProfessionalRenderer
中创建构造函数,并传入对控件的引用。
class CustomRenderer : ToolStripProfessionalRenderer
{
// All those controls derive from ToolStrip so we can use the base class here
private ToolStrip ts;
public CustomRenderer(ToolStrip ts)
{
this.ts = ts;
}
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if (ts is MenuStrip)
{
}
else if (ts is StatusStrip)
{
}
else // ts is ToolStrip
{
}
}
然后在实例化时传入引用:
toolStrip1.Renderer = new CustomRenderer(toolStrip1);
statusStrip1.Renderer = new CustomRenderer(statusStrip1);
另一种选择,已从this answer修改。
忘记ctor并反复测试Owner
,直到获得正确的父控件:
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
ToolStrip owner = e.ToolStrip;
while (owner is ToolStripDropDownMenu)
owner = (owner as ToolStripDropDownMenu).OwnerItem.Owner;
if (ts is MenuStrip)
{
}
else if (ts is StatusStrip)
{
}
else // ts is ToolStrip
{
}
}