Get Component's Parent Form

后端 未结 10 1010
再見小時候
再見小時候 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:51

    I use a recursive call to walk up the control chain. Add this to your control.

    public Form ParentForm
    {
        get { return GetParentForm( this.Parent ); }
    }
    
    private Form GetParentForm( Control parent )
    {
        Form form = parent as Form;
        if ( form != null )
        {
            return form;
        }
        if ( parent != null )
        {
            // Walk up the control hierarchy
            return GetParentForm( parent.Parent );
        }
        return null; // Control is not on a Form
    }
    

    Edit: I see you modified your question as I was typing this. If it is a component, the constructor of that component should take it's parent as a parameter and the parent should pass in this when constructed. Several other components do this such as the timer.

    Save the parent control as a member and then use it in the ParentForm property I gave you above instead of this.

提交回复
热议问题