2010-04-20 30 views
0

我希望有人能幫助我。我有以下的自定義服務器控件:自定義Web控件 - ParseChildren和資源對象

<acme:MyControl runat="sever"> 
    <MyProperty>Test String</MyProperty> 
</acme:MyControl> 

但是,如果我嘗試本地化屬性字符串,我得到一個解析錯誤:

[ParseChildren(true)] 
public class MyControl : WebControl, INamingContainer 
{ 
    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public string MyProperty 
    { 
     get;set; 
    } 
} 

它具有以下加價完美的作品

<acme:MyControl runat="sever"> 
    <MyProperty><%=(string)GetLocalResourceObject("MyResourceKey") %></MyProperty> 
</acme:MyControl> 

即使我強制類型,ASP.NET表示屬性不能接受控件作爲子項。如果我想本地化它,表達式應該如何?我可以將該屬性作爲控件標記的屬性訪問,但我更喜歡上面的標記,它看起來更優雅,更乾淨。

感謝

回答

0

添加名爲MyPropertyResourceKey第二個屬性,所以您的最終代碼如下:

[ParseChildren(true)] 
public class MyControl : WebControl, INamingContainer 
{ 
    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public string MyProperty 
    { 
     get;set; 
    } 

    string _propertyResourceKey; 
    [PersistenceMode(PersistenceMode.InnerProperty)] 
    public string MyPropertyResourceKey 
    { 
     get { 
     return _propertyResourceKey; 
     } 
     set { 
     _propertyResourceKey = value; 

     MyProperty = (string)GetLocalResourceObject(_propertyResourceKey); 
     } 
    } 
} 

編輯: 根據意見,似乎還可以有更靈活的需求方法。一般來說,如果您正在爲控件分配動態值,則需要創建數據綁定控件(如果適用)http://msdn.microsoft.com/en-us/library/ms366540.aspx

另一方面,如果控件不知道如何分配它,接受的方法是在頁面的代碼隱藏中分配屬性值。

+0

我想這將工作時,控件將只使用一個資源對象在控件的每個實例,但如果字符串可以從另一個方法派生,而不一定從資源對象? – Raybiez 2010-04-21 05:57:55