2

用法 :

    <uc1:WindowControl ID="Window_ExpoNews" runat="server" Height="265px" Title="Expo News"
    Width="100%">              
    <ContentTemplate> 
        This content will show in the center cell of this user control.
        <br />
        I can even add real controls.
        <asp:TextBox ID="TextBox1" runat="server" />
        <br />
        Good times.
    </ContentTemplate>
</uc1:WindowControl> 

控件来源:

 <asp:Panel ID="Panel2" 
           runat="server">                 
       </div>
</asp:Panel>
<asp:PlaceHolder runat="server" ID="BodyControlSpace"/>

代码背后:

public partial class Componants_WebUserControl : System.Web.UI.UserControl{

private ITemplate _ContentTemplate;

[PersistenceMode(PersistenceMode.InnerProperty)]
public ITemplate ContentTemplate
{
    get { return _ContentTemplate; }
    set { _ContentTemplate = value; }
}

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    _ContentTemplate.InstantiateIn(BodyControlSpace); 
} 

public Unit Width
{
    get {return Panel1.Width;}
    set {Panel1.Width = value;}
}

public Unit Height
{
    get {return Panel1.Height;}
    set {Panel1.Height = value;}
}

public string Title
{
    get {return lblTitle.Text;}
    set {lblTitle.Text = value;}
}

}

问题是它给了我以下错误:
对象引用未设置为对象的实例。说明:执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。

源错误:

第 21 行:{
第 22 行:base.OnInit(e);
第 23 行:_ContentTemplate.InstantiateIn(BodyControlSpace);
第 24 行:}
第 25 行:

4

2 回答 2

1

最后我发现没有人说我可以在那里添加“如果”:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    if (_ContentTemplate != null)
         _ContentTemplate.InstantiateIn(BodyControlSpace); 
} 
于 2010-08-11T07:57:12.457 回答
0

从 Web 控件中的面板类派生怎么样。它会让你和 div 围绕你的控制,但也可以让你把内容放在里面。试试这样:

public WindowControl : Panel
{
   // ...
}

或者,如果您不希望对 html 进行任何额外更改,请使用 Literal 作为基本控件:

public WindowControl : Literal
{
   // ...
}
于 2010-08-11T06:28:00.827 回答