Get Component's Parent Form

后端 未结 10 1009
再見小時候
再見小時候 2020-12-03 01:40

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

相关标签:
10条回答
  • 2020-12-03 01:59

    [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]

    Here's an article that describes how to do it for a non-visual component.

    Basically you need to add a property ContainerControl to your component:

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

    and override the Site property:

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

    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.

    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.

    0 讨论(0)
  • 2020-12-03 02:07

    If the componenet is managing other visual controls, then you should be able to get to the parent through them.

    0 讨论(0)
  • 2020-12-03 02:07

    If the component related Form is the active Form you may get it by Form.ActiveForm.

    0 讨论(0)
  • 2020-12-03 02:07

    A improvement of above is:

    public static Form ParentForm(this Control ctrl) => ctrl as Form ?? ctrl.FindForm();
    
    0 讨论(0)
提交回复
热议问题