0

我正在尝试为我的服务器控件(标题模板和内容模板)创建模板。

<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在实例化过程中使用,但我不确定如何使用他。有人知道吗?

4

1 回答 1

0

而不是从 WebControl 类继承,您可能希望查看 DataBoundControl 并覆盖“PerformDataBinding”方法。

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.databoundcontrol(v=vs.100).aspx

于 2013-09-27T11:20:57.680 回答