我正在尝试学习如何使用 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 启用对容器公共属性的访问?