Asp.net

如何使用集合屬性建構 ASP.NET 自定義控制項?

  • July 5, 2013

我想做類似的事情

<cstm:MyControl runat="server">
   <myItem attr="something" />
   <myItem attr="something" />
</cstm:MyControl>

實現這一目標所需的基本程式碼是什麼?

里克的例子顯示了類似於

<cstm:MyControl runat="server">
   <myItems>
       <cstm:myItem attr="something" />
       <cstm:myItem attr="something" />
   </myItems>
</cstm:MyControl>

如果可能的話,我更喜歡更簡潔的語法。

注意:請隨意提出更好的標題或描述。即使您沒有編輯權限,我也很高興為社區著想編輯條目。

這是一個非常簡單的範例控制項,它完全符合您的要求:

namespace TestControl
{
   [ParseChildren(true, DefaultProperty = "Names")]
   public class MyControl : Control
   {
       public MyControl()
       {
           this.Names = new List<PersonName>();
       }

       [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
       public List<PersonName> Names { get; set; }
   }

   public class PersonName
   {
       public string Name { get; set; }
   }
}

而且,這是一個範例用法:

<%@ Register Namespace="TestControl" TagPrefix="TestControl"  %>

<TestControl:MyControl runat="server" ID="MyControl1">
   <TestControl:PersonName Name="Chris"></TestControl:PersonName>
   <TestControl:PersonName Name="John"></TestControl:PersonName>
</TestControl:MyControl>

引用自:https://stackoverflow.com/questions/123616