我正在编写一个自定义ToolStripProfessionalRenderer
以以下覆盖为例:
protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
if(e.ToolStrip is MenuStrip)
{
// It never is. It's always ToolStripDropDownMenu
}
}
我猜OnRenderImageMargin
是由下拉菜单调用的,因为这是将要呈现的内容,但是我想获取导致OnRenderImageMargin
调用的父ToolStrip
/MenuStrip
/StatusStrip
。
这可能吗?
我认为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);
根据此答案修改的替代选项。
忘记 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
{
}
}