[英]How do I access ASP.NET ITemplate Container Properties
我正在嘗試學習如何將 ITemplate 用於更好的自定義控件。 我大部分時間都在工作,但我無法弄清楚如何從頁面訪問容器的任何屬性。
這是我的模板化控件:
[ParseChildren(true)]
[PersistChildren(false)]
public partial class Example : UserControl
{
private ITemplate _CustomPanelContainer;
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateContainer(typeof(CustomPanelContainer))]
[TemplateInstance(TemplateInstance.Single)]
public virtual ITemplate CustomPanel
{
get { return _CustomPanelContainer; }
set { _CustomPanelContainer = value; }
}
protected override void CreateChildControls()
{
Controls.Clear();
if (_CustomPanelContainer != null)
{
var p = new Panel();
p.ID = "CustomPanel";
Controls.Add(p);
_CustomPanelContainer.InstantiateIn(p);
}
base.CreateChildControls();
}
public class CustomPanelContainer : Panel, INamingContainer
{
private string _Test = "TESTING!";
public string TextTest
{
get
{
return _Test;
}
set
{
_Test = value;
}
}
}
}
下面是頁面實現:
<uc1:Example runat="server" ID="Example1">
<CustomPanel>
<strong>Test: </strong> <%# Container.TextTest %>
</CustomPanel>
</uc1:Example>
它主要工作,但問題是 <%# Container.TextTest %> 總是返回一個空字符串。 當我在調試器上運行它時,我在 CustomPanelContainer 的 TextTest 屬性內的行上放置了一個斷點,並且從未命中該斷點,因此實際上從未訪問過該屬性。
我在這里缺少什么? 如何通過 <%#Container 啟用對容器公共屬性的訪問?
我終於想出了如何讓它按照我想要的方式行事。
我刪除了 ITemplate 作為容器的類型並將類型設置為實際類型並向 CreateChildControls() 添加了一個 DataBind() 命令。
也許不是完全正確的方法來做到這一點,但它的工作原理。
將問題保持開放一段時間,看看是否有人提出任何批評或更好的方法,因為我真的不知道我在這里做什么。
簡化的工作代碼:
[ParseChildren(true)]
[PersistChildren(false)]
public partial class Example : UserControl
{
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public virtual CustomPanelContainer Template { get; set; }
protected override void CreateChildControls()
{
Controls.Clear();
if (Template != null)
{
Template.DataBind();
Controls.Add(Template);
}
base.CreateChildControls();
}
public class CustomPanelContainer : Panel, INamingContainer
{
public string TextTest
{
get { return "TESTING!"; }
}
}
}
頁面實現:
<uc1:Example runat="server" ID="Example">
<Template>
<strong>Test: </strong><span><%# Container.TextTest %></span>
</Template>
</uc1:Example>
編輯:這在需要隱藏模板類型時也有效。 即,上面的代碼公開了 Template 的類型以允許將 Panel 的屬性作為 Template 的屬性進行操作,而下面的代碼隱藏了 Template 的類型以阻止對其屬性的操作。
[ParseChildren(true)]
[PersistChildren(false)]
public partial class Example : UserControl
{
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
[TemplateContainer(typeof(CustomPanelContainer))]
public virtual ITemplate Template { get; set; }
protected override void CreateChildControls()
{
Controls.Clear();
if (Template != null)
{
var p = new CustomPanelContainer();
Template.InstantiateIn(p);
p.DataBind();
Controls.Add(p);
}
base.CreateChildControls();
}
public class CustomPanelContainer : Panel, INamingContainer
{
public string TextTest
{
get { return "TESTING!"; }
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.