How to get the “real” value of the Visible property?

前端 未结 4 978
执笔经年
执笔经年 2021-01-11 11:40

If you set the Visible property of a Windows Forms control to true, that property still returns false if any of the control\'s parent windows are hidden. Is there a way to g

4条回答
  •  南方客
    南方客 (楼主)
    2021-01-11 11:59

    An option that doesn't rely on reflection would be to recurse through the parents of the control hierarchy looking for one with Visible set to false.

    EDIT: See comments for significance of code.

    var frm2 = new Form {Text = "Form2"};
    var lbl = new Label {Visible = true};
    frm2.Controls.Add(lbl);
    frm2.Show();
    
    var frm1 = new Form {Text = "Form1"};
    var lblVis = new Label { Text = lbl.Visible.ToString(), Left = 10, Top = 10};
    lbl.VisibleChanged += (sender, args) => MessageBox.Show("Label Visible changed");
    var btnShow = new Button {Text = "Show", Left = 10, Top = lblVis.Bottom + 10};
    btnShow.Click += (sender, args) =>
                        {
                            frm2.Visible = true;
                            lblVis.Text = lbl.Visible.ToString();
                            };
    var btnHide = new Button {Text = "Hide", Left = 10, Top = btnShow.Bottom + 10};
    btnHide.Click += (sender, args) =>
                        {
                            frm2.Visible = false;
                            lblVis.Text = lbl.Visible.ToString();
                        };
    
    frm1.Controls.AddRange(new Control[] {lblVis, btnShow, btnHide});
    
    Application.Run(frm1);
    

提交回复
热议问题