2010-04-08 33 views
4

我想創建一個非常簡單的模板控件。我以前從來沒有這樣做過,但是我知道,如果我包含模板功能,我以前創建的很多控件都會大大受益 - 所以我現在正在學習。創建一個簡單的模板化控件。有問題

我遇到的問題是我的模板輸出在頁面上,但我的屬性值不是。所以我得到的是我在模板中包含的靜態文本。

我必須做正確的事情,因爲控制不會導致任何錯誤,所以它知道我的公共財產存在。 (例如,如果我嘗試使用Container.ThisDoesntExist,則會引發異常)。

我會很感激這方面的幫助。我可能只是一個完整的布偶而錯過了一些東西。關於簡單模板服務器控件的在線教程似乎很少,因此如果您知道一個我想知道的教程。

我的代碼的減少版本如下。

非常感謝, 詹姆斯

這裏是我的控制代碼:

[ParseChildren(true)] 
public class TemplatedControl : Control, INamingContainer 
{ 
    private TemplatedControlContainer theContainer; 

    [TemplateContainer(typeof(TemplatedControlContainer)), PersistenceMode(PersistenceMode.InnerProperty)] 
    public ITemplate ItemTemplate { get; set; } 

    protected override void CreateChildControls() 
    { 
     Controls.Clear(); 

     theContainer = new TemplatedControlContainer("Hello World"); 

     this.ItemTemplate.InstantiateIn(theContainer); 

     Controls.Add(theContainer); 
    } 
} 

這裏是我的容器代碼:

[ToolboxItem(false)] 
public class TemplatedControlContainer : Control, INamingContainer 
{ 
    private string myString; 

    public string MyString 
    { 
     get 
     { 
      return myString; 
     } 
    } 

    internal TemplatedControlContainer(string mystr) 
    { 
     this.myString = mystr; 
    } 
} 

這裏是我的標記:

<my:TemplatedControl runat="server"> 
    <ItemTemplate> 
     <div style="background-color: Black; color: White;"> 
      Text Here: <%# Container.MyString %> 
     </div> 
    </ItemTemplate> 
</my:TemplatedControl> 

回答

1

你應該在你的控件上調用方法DataBind。

一種可能性是添加在的CreateChildControls()的DataBind呼叫的方法:)

保護覆蓋無效的CreateChildControls() { Controls.Clear(;

theContainer = new TemplatedControlContainer("Hello World"); 

    this.ItemTemplate.InstantiateIn(theContainer); 

    Controls.Add(theContainer); 

    this.DataBind(); 

} 
+0

你是救世主。優秀。非常感謝 - 我知道這會很簡單!學習繼續... 乾杯, 詹姆斯 – James 2010-04-09 16:32:38

+0

高興爲您提供幫助! :) – 2010-11-19 08:06:39