2008-09-15 46 views
1

我想提出我的网页控制在设计模式更可读的,基本上我想要的变量声明的样子:Web控件属性

<cc1:Ctrl ID="Value1" runat="server">   
    <Values>string value 1</Value> 
    <Values>string value 2</Value> 
</cc1:Ctrl> 

可以说我有代码中的一个私有变量后面:

List<string> values = new List<string>(); 

那么如何让我的用户控件用标记中声明的值填充私有变量?


对不起,我应该更加明确。基本上我喜欢的了Itemplate提供的功能(http://msdn.microsoft.com/en-us/library/aa719834.aspx

但在这种情况下,你需要在运行时知道有多少模板可以instansitated,即

void Page_Init() { 
if (messageTemplate != null) { 
    for (int i=0; i<5; i++) { 
     MessageContainer container = new MessageContainer(i); 
     messageTemplate.InstantiateIn(container); 
     msgholder.Controls.Add(container); 
    } 
} 

}

在给出的示例标记的样子:

<acme:test runat=server> 
    <MessageTemplate> 
    Hello #<%# Container.Index %>.<br> 
    </MessageTemplate> 
</acme:test> 

这是非常干净的,它没有任何标记前缀等我真正想要的漂亮干净的标签。

我可能在想要标记干净时很傻,我只是想知道是否有简单的东西我错过了。

回答

2

我想你要搜索的属性:

[PersistenceMode(PersistenceMode.InnerProperty)] 

Persistence Mode

请记住,你必须注册你的命名空间和前缀:

<%@ Register Namespace="MyNamespace" TagPrefix="Pref" %> 
0

我看到两个选项,但都取决于您的Web控件实现某种集合为您的值。第一种选择是只使用控件的集合而不是私有变量。另一种选择是在运行时将控件的集合复制到您的私有变量(例如,可能在Page_Load事件处理程序中)。

假设您拥有实现项目集合(如列表框)的Web控件。标签看起来像这样在源视图:

<asp:ListBox ID="ListBox1" runat="server"> 
     <asp:ListItem>String 1</asp:ListItem> 
     <asp:ListItem>String 2</asp:ListItem> 
     <asp:ListItem>String 3</asp:ListItem> 
    </asp:ListBox><br /> 

那么你可能会使用这样的代码来加载您的私有变量:

 List<String> values = new List<String>(); 

     foreach (ListItem item in ListBox1.Items) 
     { 
      values.Add(item.Value.ToString()); 
     } 

如果你这样做在Page_Load中,你可能会想只在初始加载时执行(即不在回发)。另一方面,取决于你如何使用它,你可以使用ListBox1.Items集合而不是声明和初始化values变量。

我可以想到没有办法做到这一点声明式(因为你的列表将不会实例化,直到运行时)。