DonBoitnott
DonBoitnott

Reputation: 11025

Can I get a ToolStripControlHost reference from the control it hosts?

In the following code, a control class is created that derives from ToolStrip. That control then creates an embedded (private) ToolStripControlHost, and sets its Control to a new TextBox control. A single public member is provided, which returns a reference to the embedded TextBox control for external use. As follows...

public class StatusToolStrip : ToolStrip
{
    private ToolStripControlHost _status = new ToolStripControlHost(new TextBox());

    public TextBox StatusTextControl { get { return (_status.Control is TextBox) ? (TextBox)_status.Control : null; } }
}

My problem is that I need to get access to the ToolStripControlHost. I realize that I could simply add a public member and return it directly, but I'm curious as to why it seems to be impossible to walk backwards from hosted control to host.

So, my question is this: can I get from the TextBox control what its host is? Or, for that matter, even determine that it is hosted at all?

Thus far, I have found no way to determine, by looking at the StatusTextControl member (i.e. the hosted TextBox control), whether or not it's even in a control host, let alone what that host is.

Can this be done?

Upvotes: 0

Views: 435

Answers (1)

Loathing
Loathing

Reputation: 5256

The Parent of the control returns the ToolStrip. So then it's possible to search to ToolStrip for the control. Something like:

private static ToolStripControlHost Find(Control c) {
    var p = c.Parent;
    while (p != null) {
        if (p is ToolStrip)
            break;
        p = p.Parent;
    }
    if (p == null)
        return null;

    ToolStrip ts = (ToolStrip) p;
    foreach (ToolStripItem i in ts.Items) {
        var h = Find(i, c);
        if (h != null)
            return h;
    }
    return null;
}

private static ToolStripControlHost Find(ToolStripItem item, Control c) {
    ToolStripControlHost result = null;
    if (item is ToolStripControlHost) {
        var h = (ToolStripControlHost) item;
        if (h.Control == c) {
            result = h;
        }
    }
    else if (item is ToolStripDropDownItem) {
        var ddm = (ToolStripDropDownItem) item;
        foreach (ToolStripItem i in ddm.DropDown.Items) {
            result = Find(i, c);
            if (result != null)
                break;
        }
    }
    return result;
}

Upvotes: 1

Related Questions