【问题标题】:Custom Web Control - ParseChildren & Resource Objects自定义 Web 控件 - ParseChildren 和资源对象
【发布时间】:2010-04-20 16:00:03
【问题描述】:

我希望有人可以帮助我。我有以下自定义服务器控件:

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

它与以下标记完美配合:

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

但是如果我尝试本地化属性字符串,我会得到一个解析错误:

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

即使我强制转换类型,ASP.NET 也会指示该属性不能接受控件作为子项。如果我想本地化表达式应该如何?我可以使该属性作为控件标记的属性可访问,但我更喜欢上面的标记,它看起来更优雅和干净。

谢谢

【问题讨论】:

    标签: asp.net controls


    【解决方案1】:

    添加第二个名为 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);
          }
        }
    }
    

    编辑: 基于cmets,似乎也可能需要更灵活的方法。通常,如果您正在寻找为控件分配动态值,您将需要创建一个数据绑定控件(如果适用)http://msdn.microsoft.com/en-us/library/ms366540.aspx

    另一方面,如果控件不知道通常如何分配它,则可接受的方法是在页面的代码隐藏中分配属性值。

    【讨论】:

    • 我想当控件在控件的每个实例中只使用一个资源对象时这会起作用,但是如果字符串可以从另一种方法派生,而不一定从资源对象派生呢?跨度>
    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-22
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多