2011-02-01 56 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和一盎司的魔法,但我认为我的抽象能够理解这一点。