How do I determine visibility of a control?

前端 未结 3 2155
温柔的废话
温柔的废话 2021-02-19 20:17

I have a TabControl that contains several tabs. Each tab has one UserControl on it. I would like to check the visibility of a control x on UserControl

相关标签:
3条回答
  • 2021-02-19 20:52

    Please try this:

    bool ControlIsReallyVisible(Control C)
    {
        if (C.Parent == null) return C.Visible;
        else return (C.Visible && ControlIsReallyVisible(C.Parent));
    }
    
    0 讨论(0)
  • 2021-02-19 20:56

    I'm using this code not only checking all the ancestors visible and also who is the root control. Checking a root is needed when the control is not added on the Mainform.

    public static class StratoControlExtension
    {
        public static bool TruelyVisible(this Control control, Control expected_root)
        {
            if (control.Parent == null) { return control == expected_root && control.Visible; }
            return control.Parent.TruelyVisible(expected_root) && control.Visible;
        }
    }
    
    0 讨论(0)
  • 2021-02-19 20:59

    Unfortunately the control doesn't provide anything public that will allow you to check this.

    One possibility would be to set something in the controls 'Tag' property. The tag’s purpose is to associate user data with the control. So it can be anything not just a boolean.

    Here is the Tag property doc

    If you really want the brute force way, you can use Reflection, basically calling GetState(2):

    public static bool WouldBeVisible(Control ctl) 
    {
          // Returns true if the control would be visible if container is visible
          MethodInfo mi = ctl.GetType().GetMethod("GetState", BindingFlags.Instance | BindingFlags.NonPublic);
          if (mi == null) return ctl.Visible;
          return (bool)(mi.Invoke(ctl, new object[] { 2 }));
    }
    
    0 讨论(0)
提交回复
热议问题