扩展方法,用于确定控件在复杂层级结构中的可见性





5.00/5 (1投票)
确定在复杂(或组合)窗体中的可见性
此技巧是对以下技巧的补充:扩展方法,用于使控件在复杂层级结构中可见[^] 考虑一下你拥有多个嵌套选项卡控件的情况。
TabControlMain TabPageMainOne TabControlSubOne TabPageSubOne TabPageSubTwo MyControl TabPageMainTwo TabControlMoreSubs TabPageMoreSubsOne TabPageMoreSubsTwo确定
MyControl
当前是否在屏幕上可见的常见(朴素)方法要么繁琐,要么容易出错。 // See if MyControl is visible, if it is, I should refresh it.
bool isVisible = TabControlSubOne.ActivePage == TabPageSubOne
&& TabControlMain.ActivePage == TabPageMainOne;
这种方法在某种程度上有效,直到屏幕变成一个 usercontrol
并且放置在第三个 TabControl
上。现在,又有一个控件需要考虑,但你的代码并没有为此设计。这在动态组合的屏幕中是一种常见情况。 这种方法在屏幕本身内部也会出现问题,并且与可维护性有关。 如果我们重新设计屏幕并决定将 MyControl
移动到 TabPageMoreSubsTwo
,会发生什么?现在我们的测试无效了,但由于代码本身并不明显错误,我们可能在太晚的时候(生产环境)才发现问题。 显然,这不太理想。 出了什么问题?让我们回到原始问题和它的实现方式。 问题是“我的控件是否可见”,但它被实现为:“一些选项卡控件是否具有正确的活动页面属性”。 实现的问题在于“一些”这个词,正如我上面所示,检查“一些”可能不够,甚至可能是错误的。 为了解决这个问题,我们应该将其实现为“所有选项卡控件是否具有正确的活动页面属性”? 这就是这个扩展方法所做的。 用法 // See if MyControl is visible, if it is, I should refresh it.
bool isVisible = MyControl.IsMyControlVisible();
这个扩展方法有一个很好的好处,就是我们抽象掉了“如何”,只保留了源代码的“是什么”。 可读性 +1。/// <summary>
/// Checks to see whether the provided subject is visible in the tabpage hierarchy of a form.
/// It navigates up the parent-hierarchy and when it encounters a tabControl, checks to see whether
/// the current parent is actually the active tabpage. When the result of this check is false,
/// the functions exits with false as a result.
/// Supports TabControls and Infragistics.UltraTabPageControl
/// </summary>
/// <param name="subject">The subject.</param>
/// <returns>
/// True is all tabpages where the active control.
/// </returns>
public static bool IsMyControlVisible(this Control subject)
{
if ((subject == null) || (subject.Parent == null))
{
return false;
}
Control testSubject = subject;
TabControl parentPageControl = null;
UltraTabPageControl aPage = null;
Control testSubject = subject;
while (testSubject != null)
{
TabPage asTabPage = (testSubject as TabPage);
if (asTabPage == null)
{
UltraTabPageControl asUltraTabPage = testSubject as UltraTabPageControl;
if (asUltraTabPage != null)
{
if (asUltraTabPage.TabControl == null)
{
return false;
}
if (asUltraTabPage.TabControl.SelectedTab != asUltraTabPage.Tab)
{
return false;
}
}
}
else
{
TabControl parentPageControl = asTabPage.Parent as TabControl;
if (parentPageControl == null)
{
return false;
}
if (parentPageControl.SelectedTab != testSubject)
{
return false;
}
testSubject = parentPageControl;
}
if (testSubject != null)
{
testSubject = testSubject.Parent;
}
}
return true;
}