Tuesday, September 13, 2011

Detecting the parent Form from Component class

Component is a class that allows you to build non-visual control. For example, Timer class. By the problem is that it does not have a intuitive way to get the parent control.

Below is the code that will get the parent control reference and save the reference during the design time. Please take note the following code will work when you are dragging a control from the Toolbox onto the Form. For those Component that has already dropped on the Form before you added codes below, it will not work.

private ContainerControl _containerControl = null;
        public ContainerControl ContainerControl
        {
            get { return _containerControl; }
            set { _containerControl = value; }
        }

        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;
                    }
                }
            }
        }

No comments:

Post a Comment