我可以从它托管的控件中获取 ToolStripControlHost 引用吗?
Can I get a ToolStripControlHost reference from the control it hosts?
在以下代码中,创建了一个派生自 ToolStrip
的控件 class。然后该控件创建一个嵌入式(私有)ToolStripControlHost
,并将其 Control
设置为新的 TextBox
控件。提供了一个 public 成员,它 return 是对供外部使用的嵌入式 TextBox
控件的引用。如下...
public class StatusToolStrip : ToolStrip
{
private ToolStripControlHost _status = new ToolStripControlHost(new TextBox());
public TextBox StatusTextControl { get { return (_status.Control is TextBox) ? (TextBox)_status.Control : null; } }
}
我的问题是我需要访问 ToolStripControlHost
。我意识到我可以简单地添加一个 public 成员并直接 return 它,但我很好奇为什么似乎不可能从托管控件向后移动到主机。
所以,我的问题是:我可以从 TextBox
控制它的主机是什么吗?或者,就此而言,甚至确定它完全托管?
到目前为止,我还没有办法通过查看 StatusTextControl
成员(即托管的 TextBox
控件)来确定它是否在控制主机中,更不用说了主机是什么。
这可以做到吗?
Parent
控件returnsToolStrip
。这样就可以搜索到 ToolStrip
来查找控件。类似于:
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;
}
在以下代码中,创建了一个派生自 ToolStrip
的控件 class。然后该控件创建一个嵌入式(私有)ToolStripControlHost
,并将其 Control
设置为新的 TextBox
控件。提供了一个 public 成员,它 return 是对供外部使用的嵌入式 TextBox
控件的引用。如下...
public class StatusToolStrip : ToolStrip
{
private ToolStripControlHost _status = new ToolStripControlHost(new TextBox());
public TextBox StatusTextControl { get { return (_status.Control is TextBox) ? (TextBox)_status.Control : null; } }
}
我的问题是我需要访问 ToolStripControlHost
。我意识到我可以简单地添加一个 public 成员并直接 return 它,但我很好奇为什么似乎不可能从托管控件向后移动到主机。
所以,我的问题是:我可以从 TextBox
控制它的主机是什么吗?或者,就此而言,甚至确定它完全托管?
到目前为止,我还没有办法通过查看 StatusTextControl
成员(即托管的 TextBox
控件)来确定它是否在控制主机中,更不用说了主机是什么。
这可以做到吗?
Parent
控件returnsToolStrip
。这样就可以搜索到 ToolStrip
来查找控件。类似于:
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;
}