2010-04-16 13 views
0

我一直在關注如何在ListView控件中使用多個ItemTemplates。將對象傳遞給動態加載的ListView ItemTemplate

雖然下面這個例子確實會產生輸出,但我想知道如何將一個對象psas到ItemTemplate的用戶控件,我似乎無法做到/弄清楚。

protected void lvwComments_OnItemCreated(object sender, ListViewItemEventArgs e) 
    { 
     ListViewDataItem currentItem = (e.Item as ListViewDataItem); 
     Comment comment = (Comment)currentItem.DataItem; 

     if (comment == null) 
      return; 

     string controlPath = string.Empty; 

     switch (comment.Type) 
     { 
      case CommentType.User: 
       controlPath = "~/layouts/controls/General Comment.ascx"; 
       break; 
      case CommentType.Official: 
       controlPath = "~/layouts/controls/Official Comment.ascx"; 
       break; 
     } 
     lvwComments.ItemTemplate = LoadTemplate(Controlpath); 
    } 

的用戶控制如下:

public partial class OfficialComment : UserControl 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 

    } 
} 

在該示例中,這些值是在ASCX頁輸出:

<%# Eval("ItemName") %> 

但是我需要訪問列表項中這個控制做其他的邏輯。我無法弄清楚我如何通過我的評論項發送。發件人對象和EventArgs不包含信息。

編輯: 理想情況下,我想獲得一個解釋,控制使用<%#評估和演示%>語句時如何訪問DataItem的。我已經能夠確定,以下方式獲得當前項目:

我已經創建了一個自定義的ListView控件,該控件在ItemCreating上設置了dataItemIndex。

在我的官方評論的控制,我添加以下內容:

List<Comment> commentList = ((CommentListView)this.Parent.Parent.Parent).DataSource as List<Comment>; 

if (commentList != null) 
{ 
    int currentIndex = ((ListViewDataItem)this.Parent).DataItemIndex; 
    Comment currentItem = commentList[currentIndex]; 
} 

回答

0

雖然有動態項模板文件,沒有例子進展通過對訪問數據的其他的<%#評估和演示%>的功能。在嘗試了一些方法後,我的問題就顯示出來了,我並不喜歡遞歸遍歷控件樹。

我所能做的就是創建一個繼承自UserControl的類。這個類將定義我的DataItem:

public partial class ListViewTemplateControl<T> : UserControl where T : class 
{ 
    public T CurrentItem { get; set; } 
} 

然後,在我的ListView,我可以執行以下操作:

protected void lvwComments_OnItemCreated(object sender, ListViewItemEventArgs e) 
    { 
     ListViewDataItem currentItem = (e.Item as ListViewDataItem); 
     Comment comment = (Comment)currentItem.DataItem; 

     if (comment == null) 
      return; 

     string controlPath = string.Empty; 

     switch (comment.Type) 
     { 
      case CommentType.User: 
       controlPath = "~/layouts/controls/General Comment.ascx"; 
       break; 
      case CommentType.Official: 
       controlPath = "~/layouts/controls/Official Comment.ascx"; 
       break; 
     } 

     ListViewTemplateControl<Comment> templateControl = LoadControl(controlPath) as ListViewTemplateControl<Comment>; 

     if (templateControl != null) 
     { 
      templateControl.CurrentItem = comment; 
      templateControl.ID = comment.ItemID; 
      lvwComments.Controls.Add(templateControl); 
     } 
    } 

在我的模板控制,我現在可以基於CURRENTITEM履行我所有的自定義邏輯(DataItem),我通過。唯一需要注意的是,<%#Eval%>函數現在不起作用。