如果容器页面上的 UC 设置为 Visible false,我正在考虑停止页面加载的执行。现在我遵循以下逻辑
public class TestControl : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (this.Visible)
{
//do heavy operation
}
}
}
即我会检查该控件在UC的页面加载中是否可见,如果为true,则只在那里进行操作。还有其他更好的方法吗?我的申请中有很多 UC。如果Visible false,是否有一些通用逻辑来停止UC页面加载的执行。
最佳答案
Control 类的 Visible
属性仅确定是否呈现 Control,但它对控件生命周期的其余部分没有影响。
来自MSDN :
If this property is false, the server control is not rendered. You should take this into account when organizing the layout of your page. If a container control is not rendered, any controls that it contains will not be rendered even if you set the Visible property of an individual control to true. [...]
这是有道理的,因为这样您就可以拥有仍然执行特定操作的不可见控件。您也可以通过不向其中放入任何内容来做到这一点,但它们可能仍然会呈现一些空格或换行符。将 Visible
设置为 false 是最简洁的方法。
如果控件不可见,我认为没有更好的方法来阻止代码的执行,但我认为您的解决方案足够干净。
作为替代方案,您可以将代码放入 OnPreRender 事件中,该事件仅在控件可见时触发。但请记住,这是 Control Lifecycle 中的后续步骤。 .
public class TestControl : System.Web.UI.UserControl
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
// Your code here
}
}
关于.net - 如何在 Visible false 的页面加载时停止 UC 的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7371417/