2011-03-03 122 views
3

例如:ASP.NET自定義控件,可以模板字段有屬性嗎?

<uc:AdmiralAckbar runat="server" id="myCustomControl"> 
<Warning SomeAttribute="It's A Trap"> 
My Data 
</Warning> 
</uc:AdmiralAckbar> 

我不知道如何添加SomeAttribute。有任何想法嗎?

代碼,而屬性是:

private ITemplate warning = null; 

    [TemplateContainer(typeof(INamingContainer))] 
    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public ITemplate Warning 
    { 
     get 
     { 
      return warning; 
     } 
     set 
     { 
      warning = value; 
     } 
    } 

回答

4

答案是肯定的。

爲此,您應該創建一個類型,實現ITemplate接口並在其中添加一個自定義屬性/屬性(我在示例中添加了屬性Name);還添加了一個繼承自Collection<YourTemplate>的類。

這裏是做的一個例子:

public class TemplateList : Collection<TemplateItem> { } 

public class TemplateItem : ITemplate 
{ 
    public string Name { get; set; } 

    public void InstantiateIn(Control container) 
    { 
     var div = new HtmlGenericControl("div"); 
     div.InnerText = this.Name; 

     container.Controls.Add(div); 
    } 
} 

和控制自己:

[ParseChildren(true, "Templates"), PersistChildren(false)] 
public class TemplateLibrary : Control 
{ 
    public TemplateLibrary() 
    { 
     Templates = new TemplateList(); 
    } 

    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public TemplateList Templates { get; set; } 

    protected override void RenderChildren(HtmlTextWriter writer) 
    { 
     foreach (var item in Templates) 
     { 
      item.InstantiateIn(this); 
     } 

     base.RenderChildren(writer); 
    } 
} 

最後使用的例子:

<my:TemplateLibrary runat="server"> 
    <my:TemplateItem Name="hello" /> 
    <my:TemplateItem Name="there" /> 
</my:TemplateLibrary> 

順便說一句,你也可以用它作爲:

<my:TemplateLibrary runat="server"> 
    <Templates> 
     <my:TemplateItem Name="hello" /> 
     <my:TemplateItem Name="there" /> 
    </Templates> 
</my:TemplateLibrary> 

效果會一樣。

+0

嗨。當我嘗試從銘牌繼承我得到一個味精「類只能從其他類繼承」謝謝 – 2011-06-30 12:26:09

+0

@Yisman,假設你在'VB'下,應該使用'實現'而不是'繼承'(因爲這是一個接口)。 – Alex 2011-06-30 13:34:34

+0

也許我錯過了一些東西,但是這段代碼會生成ITemplate對象(所謂的自定義類型),它*不具有在它們下面構建的標記控制樹?實現一個自定義的'InstantiateIn'類* *擊敗了標記模板的重點。 – 2012-09-20 01:47:27

相關問題