2010-04-20 47 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