你需要的是http://msdn.microsoft.com/en-us/library/system.web.ui.itemplate.aspx
HTML
<test:NamingControl runat="server" ID="NamingControl" TitleFormat="This is myTitle">
<TitleFormatTemplate>
My title is <%# Container.TitleFormat %>
</TitleFormatTemplate>
</test:NamingControl>
用戶控件
public partial class MyUserControl : System.Web.UI.UserControl
{
private ITemplate template;
protected void Page_Load(object sender, EventArgs e)
{
}
public string TitleFormat
{
get;
set;
}
[PersistenceMode(PersistenceMode.InnerProperty),
TemplateContainer(typeof(TitleFormatTemplate))]
public ITemplate TitleFormatTemplate
{
get { return template; }
set { template = value; }
}
protected override void CreateChildControls()
{
base.CreateChildControls();
TitleFormatTemplate t = new TitleFormatTemplate();
t.TitleFormat = this.TitleFormat;
template.InstantiateIn(t);
this.Controls.Add(t);
this.DataBind();
}
}
子控件 - 作INamingContainer
public class TitleFormatTemplate : Control, INamingContainer
{
private string _TitleFormat = "";
public string TitleFormat
{
get { return _TitleFormat; }
set { _TitleFormat = value; }
}
}
的更簡單的方法 - 沒有更多TitleFormat標籤
MyUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs"
Inherits="testgingweb.usrcontrols.MyUserControl" %>
<a href="www.somewhere.com"><h3><asp:Label runat="server" ID="PassedValueLabel"></asp:Label</h3></a>
代碼隱藏 - MyUserControl.ascx.cs
public string TitleFormat
{
get { return ViewState["TitleFormat"]; }
set { ViewState["TitleFormat"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
PassedValueLabel.Text = String.Format("Whatever {0} here", this.TitleFormat);
}
HTML
<test:MyUserContorl runat="server" ID="NamingControl" TitleFormat="This is myTitle">
</test:MyUserContorl>
請注意,我沒有TitleFormat
標籤了。
首先,感謝您的回答。我不認爲這會適用於我正在做的事情。你有點重新定義了我的目標。我將插入一個動態數量的標題,所以我不能爲每個標題添加一個屬性。我並不需要ITemplate或任何在控件中實例化的東西。這將是矯枉過正。我只想在標記中聲明一個字符串屬性作爲用戶控件的子元素。字符串屬性的值恰好是HTML。你是說不能做? – xr280xr
您用作控件的子元素的標記''只能用於ITemplate。沒有這一點,你不能以聲明的方式去做。檢查我更新的答案以查看其他方法 –
codingbiz
「您用作控件的子元素的標記只能使用ITemplate」 - False。看到明顯的答案。 –
xr280xr