我有几个派生自 BaseCtrl
的用户控件。
BaseCtrl
没有 .ascx
标记页,只有 .cs
文件中的代码定义。
我确信所有从 BaseCtrl
显式派生的控件都有一个 ChildControl
实例,其 ID CC
在其 中定义.ascx
标记页面。
我需要从 BaseCtrl
代码中检索派生控件中存在的 CC
实例。
派生1.ascx
...
<uc1:ChildControl runat="server" ID="CC" />
...
派生1.ascx.cs
public class Derived1 : BaseCtrl { ... }
派生2.ascx
...
<uc1:ChildControl runat="server" ID="CC" />
...
派生2.ascx.cs
public class Derived2 : BaseCtrl { ... }
BaseCtrl.cs
public class BaseCtrl : UserControl
{
protected ChildControl DerivedCC
{
get { /* ??? */ }
};
}
如何在 BaseCtrl
的 DerivedCC
属性中获取派生类的子控件实例?
是否可以在页面生命周期内随时获取,或者派生控件是否需要完全加载/初始化?
最佳答案
选项 1:使用 FindControl通过 ID 查找 CC
子控件的方法:
public class BaseCtrl : UserControl
{
protected ChildControl DerivedCC
{
get { return (ChildControl)this.FindControl("CC"); }
}
}
选项 2:向 BaseCtrl
添加名为 CC
的 protected 字段,并删除自动生成的 CC
每个派生用户控件的设计器文件中的字段:
public class BaseCtrl : UserControl
{
protected ChildControl CC;
protected ChildControl DerivedCC
{
get { return this.CC; }
}
}
(当然,您可能希望完全删除 DerivedCC
属性,因为它是多余的。)
选项 3:将 DerivedCC
设为 BaseCtrl
中的抽象属性,并在每个派生用户控件中覆盖它:
public abstract class BaseCtrl : UserControl
{
protected abstract ChildControl DerivedCC { get; }
}
public class Derived1 : BaseCtrl
{
protected override ChildControl DerivedCC
{
get { return this.CC; }
}
}
// And similarly for Derived2.
所有三个选项都允许您在页面生命周期中的任何时刻访问 DerivedCC
,但在控件的构造函数中除外(此时该属性将返回 null)。
选项 1 的优点是它需要对您当前拥有的代码进行最少的更改。
选项 2 的优点是它可以说比调用 FindControl 更简单、更清晰。
选项 3 的优点是它有助于在编译时验证每个派生用户控件中是否确实具有 CC
子控件。
关于c# - ASP.NET UserControl 继承 - 从基类获取派生类控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148187/