[英]Creating asp.net server control template
我正在尝试为服务器控件创建模板(标题模板和内容模板)。
<uc:MyControl ID="myConrol1" runat="server">
<CaptionTemplate>
<%# Eval("MyCaption") %>
</CaptionTemplate>
<ContentTemplate>
<b><%# Eval("MyContent") %></b>
</ContentTemplate>
</uc:MyControl>
然后给出带有数据源的模板
var ds = new List<CarouselItem>
{
new CarouselItem()
{
MyCaption = "Slide 1 caption",
MyContent = "Slide 1 content"
},
new CarouselItem()
{
MyCaption = "Slide 2 caption",
MyContent = "Slide 2 content"
}
};
myConrol1.DataSource = ds;
myConrol1.DataBind();
但是,我尝试过的方法对我不起作用。 这是我尝试实现此功能的代码。
[Browsable(false), DefaultValue(null), Description("The content template."), TemplateContainer(typeof(MyItemContainer)), PersistenceMode(PersistenceMode.InnerProperty)]
public virtual ITemplate ContentTemplate { get; set; }
[Browsable(false), DefaultValue(null), Description("The caption template."), TemplateContainer(typeof(MyItemContainer)), PersistenceMode(PersistenceMode.InnerProperty)]
public virtual ITemplate CaptionTemplate { get; set; }
然后我创建了
public class MyItemContainer : WebControl, INamingContainer
{
private readonly MyItem item;
public MyItemContainer (MyItem ai)
{
item = ai;
}
public MyItem DataItem
{
get { return item; }
}
}
然后在bind方法中将InstantiateIn写入此类
foreach (object dataSourceObject in ds)
{
var item = new MyItem
{
Caption = new PlaceHolder(),
Content = new PlaceHolder(),
DataItem = dataSourceObject
};
if (ContentTemplate != null)
{
MyAccordionItemContainer cc = new MyAccordionItemContainer(item);
ContentTemplate.InstantiateIn(cc);
item.Content.Controls.Add(cc);
}
if (CaptionTemplate != null)
{
MyAccordionItemContainer cc = new MyAccordionItemContainer(item);
CaptionTemplate.InstantiateIn(cc);
item.Caption.Controls.Add(cc);
}
item.DataBind();
}
页面中的所有内容都不为空且未绑定。 似乎我没有在实例化过程中使用dataSourceObject
,但是我不确定如何使用他。 这里有人知道吗?
与其从WebControl类继承,不如直接看一下DataBoundControl并覆盖“ PerformDataBinding”方法。
http://msdn.microsoft.com/zh-cn/library/system.web.ui.webcontrols.databoundcontrol(v=vs.100).aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.