【问题标题】:Define a property of a base class (ascx) in a custom UserControl, and instanciate a child class in the aspx在自定义的UserControl中定义一个基类(ascx)的属性,并在aspx中实例化一个子类
【发布时间】:2011-05-23 08:50:13
【问题描述】:

我定义了 3 个这样的自定义用户控件:

public partial abstract class MyAbstractControl : Usercontrol{
  // Base class definition here, with common property and methods
  public string CommonAttribute {get; set;}
}

public partial class MyConcreteControl1 : MyAbstractControl{
  // Some specific stuff here
}

public partial class MyConcreteControl2 : MyAbstractControl{
  // Other specific but different stuff here
}

然后我定义了另一个具有基类属性的 UserControl:

public partial class MyBeautifulControl : UserControl{
  [PersistenceMode(PersistenceMode.InnerProperty)]
  public MyAbstractControl ChildElement{get;set;}
}

在 aspx 文件中,我正在使用这个控件,但我想定义一个 MyConcreteControl1 的实例,而不是 MyAbstractControl

但如果我写:

<MyBeautifulControl runat="server" id="beautiful">
  <ChildElement commonAttribute="value" />
</MyBeautifulControl>

ChildElement 只能定义为 MyAbstractControl 实例。我想根据上下文创建一个 MyConcreteControl1MyConcreteControl2 实例,但我不知道如何。

【问题讨论】:

    标签: asp.net user-controls properties ascx base-class


    【解决方案1】:

    使用System.Web.UI.TemplateContainerAttribute

    [PersistenceMode(PersistenceMode.InnerProperty), 
     TemplateContainer(typeof(MyConcreteControl))]
    public MyAbstractControl ChildElement{get;set;}
    

    有关详细信息,请参阅documentation。还有一个HOWTO关于。

    【讨论】:

    • 如果我按照你的建议去做,我需要提前知道我会在 ChildElement 属性中实例化一个 MyConcreteControl1 对吧?
    • 我不需要用不同的模板来展示同一个模型,但是我需要用不同的属性来实例化不同的对象。
    猜你喜欢
    • 1970-01-01
    • 2019-01-29
    • 2019-03-12
    • 2013-09-04
    • 2022-01-16
    • 1970-01-01
    • 2019-11-11
    • 2016-11-05
    • 1970-01-01
    相关资源
    最近更新 更多