2011-02-01 57 views
0

我與模板化的用戶控制的工作。在控制的最終的標記,該數據正由集裝箱關鍵字訪問。我自由地使用了「關鍵字」這個詞,因爲我不明白這是一個關鍵字,還是容器詞來自哪裏。以下是我的書中的一個例子。ASP.NET模板化用戶控件「容器」關鍵字

//Address User Control markup 
<%@ Control Language="C#" AutoEventWireup="true" 
CodeFile="AddressUcTemplated.ascx.cs" Inherits="AddressUcTemplated" %> 
<asp:PlaceHolder runat="server" 
ID="PlaceHolderAddressTemplate"> 
</asp:PlaceHolder> 

-

//Address User Control code-behind 
public partial class AddressUcTemplated : 
System.Web.UI.UserControl 
{ 
protected void Page_Init(object sender, EventArgs e) 
{ 
//clear the controls from the placeholder 
PlaceHolderAddressTemplate.Controls.Clear(); 
if (LayoutTemplate == null) 
{ 
PlaceHolderAddressTemplate.Controls.Add(
new LiteralControl("No template defined.")); 
} 
else 
{ 
AddressUcContainer container = new 
AddressUcContainer(this.Address); 
this.LayoutTemplate.InstantiateIn(container); 
//add the controls to the placeholder 
PlaceHolderAddressTemplate.Controls.Add(container); 
} 
} 
[PersistenceMode(PersistenceMode.InnerProperty)] 
[TemplateContainer(typeof(AddressUcContainer))] 
public ITemplate LayoutTemplate { get; set; } 
public Address Address { get; set; } 
} 

-

//Naming Container Class 
    public class AddressUcContainer : Control, INamingContainer 
    { 
    public AddressUcContainer(Address address) 
    { 
    this.Address = address; 
    } 
    public Address Address { get; set; } 
    } 

-

 //Page using the user control; the Container keyword is confusing me in the below //statement 
... 
<%@ Register src="AddressUcTemplated.ascx" tagname="AddressUcTemplated" 
tagprefix="uc1" %> 
     <uc1:AddressUcTemplated ID="AddressUcTemplated1" 
     runat="server" AddressType="Home"> 
     <LayoutTemplate> 
     <h1>Edit Home Address</h1> 
     <table> 
     <tr> 
     <td>Address Line 1:</td> 
     <td> 
     <asp:TextBox ID="TextBoxAddress" runat="server" 
     Text="<%#Container.Address.AddressLine1%>"></asp:TextBox> 
     ... 

回答

0

我的示例代碼如下:

<asp:Repeater runat="server"> 
    <ItemTemplate><%# Container.DataItem %></ItemTemplate> 
</asp:Repeater> 

智能感知狀態指出Container是RepeaterItem類型的字段/變量。變量部分告訴我,這是一些特殊的解析,因爲如果它是公共的東西,它最可能是一個屬性。

不管怎樣,我的代碼被解析成,其中包括下列數據綁定代碼:

public void __DataBind__control4(object sender, EventArgs e) { 
    var target = (DataBoundLiteralControl)sender; 
    var Container = (RepeaterItem)target.BindingContainer; 
    target.SetDataBoundString(0, Convert.ToString(Container.DataItem, CultureInfo.CurrentCulture)); 
} 

<%# ... %>是DataBoundLiteralControl,並Container是的裸智能感知變量。這也表明,有一個target變量,它確實在智能感知顯示出來,但沒有任何問題彙總。請注意,這也使您可以訪問生成的類中的所有私有內容,例如__fileDependencies

<%# target %>作品,而<%# dummy %>沒有。雖然它,<%# __DataBind__control4(null, null) %>「爲‘System.Convert.ToString(對象,System.IFormatProvider)’有一些無效參數的最佳重載的方法匹配」創建兩個編譯錯誤,1),2)「參數1:不能從轉換'無效'到'對象'「。

這看起來像無論是<%# ... %>之間寫的一個簡單的情況下被放置在Convert.ToString(..., CultureInfo.CurrentCulture)。它可能更先進,涉及不同的ControlBuilders,TemplateParsers和一盎司的魔法,但我認爲我的抽象能夠理解這一點。