[英]How do I determine visibility of a control?
我有一個TabControl
包含幾個選項卡。 每個選項卡上都有一個UserControl
。 我想檢查來自UserControl
B
UserControl
A
上的UserControl
x
的可見性。 我認為從UserControl
B
做x.Visible
就足夠了。 事實證明,它在調試器中顯示為false
,即使我將其明確設置為true
並且從未更改過。 然后我在MSDN上閱讀Control.Visible :
即使Visible設置為true,如果用戶在其他控件后面被遮擋,控件也可能不可見。
令我驚訝的是,這不會奏效。 現在我想知道如何判斷控件x
是否可以從不同的UserControl
看到。 如果可能的話,我想避免使用布爾值。 有沒有人碰到這個並找到了解決方案?
注意:在這種情況下, Control.IsAccessible
似乎也是假的。
不幸的是,控件沒有提供任何公開的內容,可以讓你檢查這個。
一種可能性是在控件'Tag'屬性中設置一些東西。 標簽的目的是將用戶數據與控件相關聯。 所以它可以是任何東西,而不僅僅是一個布爾值。
如果你真的想要蠻力方式,你可以使用Reflection,基本上調用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 }));
}
請試試這個:
bool ControlIsReallyVisible(Control C)
{
if (C.Parent == null) return C.Visible;
else return (C.Visible && ControlIsReallyVisible(C.Parent));
}
我正在使用此代碼不僅檢查所有可見的祖先以及誰是根控件。 如果未在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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.