获取组件的父窗体 [英] Get Component's Parent Form
问题描述
我有管理其他可视控件的非可视组件。
I have a non-visual component which manages other visual controls.
我需要有该组件上运行的表单的引用,但我不知道如何得到它。
I need to have a reference to the form that the component is operating on, but i don't know how to get it.
我不确定加入指定为控制父构造的,因为我想通过在组件只是被投进了设计师的工作。
I am unsure of adding a constructor with the parent specified as control, as i want the component to work by just being dropped into the designer.
另外以为我已经是有父母的房产作为控制,默认值是'我'
The other thought i had was to have a Property of parent as a control, with the default value as 'Me'
任何建议将是巨大的。
编辑:
要澄清一下,这是一个组件,不是控制,在这里看到:<一href=\"http://msdn.microsoft.com/en-us/library/system.componentmodel.component.aspx\">ComponentModel.Component
To clarify, this is a component, not a control, see here :ComponentModel.Component
推荐答案
[据了解,下面只有的ISite技术工程在设计时是非常重要的。因为一个ContainerControl是公众和被分配一个值的VisualStudio会写初始化code设置它在运行时。站点设置在运行时,但你不能从它那里得到一个ContainerControl]
[It is important to understand that the ISite technique below only works at design time. Because ContainerControl is public and gets assigned a value VisualStudio will write initialization code that sets it at run-time. Site is set at run-time, but you can't get ContainerControl from it]
基本上你需要一个属性一个ContainerControl添加到您的组件:
Basically you need to add a property ContainerControl to your component:
public ContainerControl ContainerControl
{
get { return _containerControl; }
set { _containerControl = value; }
}
private ContainerControl _containerControl = null;
和覆盖站点属性:
public override ISite Site
{
get { return base.Site; }
set
{
base.Site = value;
if (value == null)
{
return;
}
IDesignerHost host = value.GetService(
typeof(IDesignerHost)) as IDesignerHost;
if (host != null)
{
IComponent componentHost = host.RootComponent;
if (componentHost is ContainerControl)
{
ContainerControl = componentHost as ContainerControl;
}
}
}
}
如果你这样做,一个ContainerControl将被初始化由设计师来引用包含窗体。链接的文章解释了它的更多细节。
If you do this, the ContainerControl will be initialized to reference the containing form by the designer. The linked article explains it in more detail.
来看看如何做事情的一个好方法是看在.NET Framework中有类似你想用的工具,如卢茨反射哪些行为类型的实现。在这种情况下,System.Windows.Forms.ErrorProvider就是一个很好的例子来看看:需要知道它含有形成组件
A good way to see how to do things is to look at the implementation of Types in the .NET Framework that have behaviour similar to what you want with a tool such as Lutz Reflector. In this case, System.Windows.Forms.ErrorProvider is a good example to look at: a Component that needs to know its containing Form.
这篇关于获取组件的父窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!