获取ToolStripDropDownMenu的(ToolStrip)父级

时间:2015-06-11 15:27:03

标签: c# .net winforms toolstrip toolstripdropdown

我正在撰写自定义ToolStripProfessionalRenderer

例如,以下覆盖:

protected override void OnRenderImageMargin(ToolStripRenderEventArgs e)
{
    if(e.ToolStrip is MenuStrip)
    {
        // It never is. It's always ToolStripDropDownMenu
    }
}

我想下拉菜单会调用OnRenderImageMargin,因为这是要呈现的内容,但我希望得到父ToolStrip / MenuStrip / StatusStrip导致OnRenderImageMargin调用。

这可能吗?

1 个答案:

答案 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
    {
    }      
}