这是我的自定义服务器控件的示例代码:
[Designer(typeof(ContainerControlDesigner))]
[ToolboxData("<{0}:BlocArrondi runat=server><ContenuPrincipal></ContenuPrincipal></{0}:BlocArrondi>")]
public class BlocArrondi : WebControl
{
private ITemplate _ContenuPrincipal;
protected Panel _PanelContenuPrincipal = new Panel();
public BlocArrondi()
: base(HtmlTextWriterTag.Div)
{
}
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate ContenuPrincipal
{
get { return _ContenuPrincipal; }
set { _ContenuPrincipal = value; }
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
_PanelContenuPrincipal.ID = "PanelPrincipal";
this.Controls.Add(_PanelContenuPrincipal);
if (_ContenuPrincipal != null)
_ContenuPrincipal.InstantiateIn(_PanelContenuPrincipal);
}
}
这里的实施:
<controls:BlocArrondi runat="server">
<ContenuPrincipal>
<asp:Label id="LabelInfo" runat="server" />
</ContenuPrincipal>
</controls:BlocArrondi>
我的标签LabelInfo可以在后面的代码上访问,很棒!
但是如果我在Repeater或ListView中使用我的自定义控件,我不能在ContenuPrincipal模板中使用Container.DataItem属性:
<asp:Repeater id="RepeaterInfos" runat="server">
<ItemTemplate>
<controls:BlocArrondi runat="server">
<ContenuPrincipal>
<asp:Label runat="server" Text="<%# (Container.DataItem as MsgInfo).DisplayMessage() " />
</ContenuPrincipal>
</controls:BlocArrondi>
</ItemTemplate>
</asp:Repeater>
错误消息:
'System.Web.UI.Control'不包含'DataItem'的定义,并且没有可以找到接受类型'System.Web.UI.Control'的第一个参数的扩展方法'DataItem'(你丢失了吗?) using指令或程序集引用?)
如何在我的控件的ContenuPrincipal模板中使用Container.DataItem属性?
答案 0 :(得分:4)
我使用IDataItemContainer继承的自定义TemplateContainer解决了我的问题:
public class BlocArrondiContainer : Panel, IDataItemContainer
更改:
protected Panel _PanelContenuPrincipal = new Panel();
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
public ITemplate ContenuPrincipal
{
get { return _ContenuPrincipal; }
set { _ContenuPrincipal = value; }
}
通过:
protected BlocArrondiContainer _PanelContenuPrincipal = new BlocArrondiContainer ();
[PersistenceMode(PersistenceMode.InnerProperty)]
[TemplateInstance(TemplateInstance.Single)]
[TemplateContainer(typeof(BlocArrondiContainer))]
public ITemplate ContenuPrincipal
{
get { return _ContenuPrincipal; }
set { _ContenuPrincipal = value; }
}
重写BlocArrondi类上的OnDataBinding方法:
protected override void OnDataBinding(System.EventArgs e)
{
if (NamingContainer is IDataItemContainer)
_PanelContenuPrincipal.DataItem = (NamingContainer as IDataItemContainer).DataItem;
base.OnDataBinding(e);
}