首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >动态创建UIHint属性

动态创建UIHint属性
EN

Stack Overflow用户
提问于 2011-09-06 22:21:27
回答 1查看 1.1K关注 0票数 2

我想要动态地将UIHint属性注入模型对象。我一直在使用ICustomTypeDescriptor创建一个类,该类将把UIHint注入到一个对象的实例中:

代码语言:javascript
复制
public sealed class UIHintDescriptionProvider : TypeDescriptionProvider
{
    private string PropertyName;
    private string HintValue;

    public UIHintDescriptionProvider(TypeDescriptionProvider parent, string propertyName, string hintValue)
        : base(parent)
    {
        this.PropertyName = propertyName;
        this.HintValue = hintValue;
    }

    public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
    {
        return new UIHintDescriptor(base.GetTypeDescriptor(objectType, instance), this.PropertyName, this.HintValue);
    }
}

public sealed class UIHintDescriptor : CustomTypeDescriptor
{
    private string PropertyName;
    private string HintValue;

    internal UIHintDescriptor(ICustomTypeDescriptor parent, string propertyName, string hintValue)
        : base(parent)
    {
        this.PropertyName = propertyName;
        this.HintValue = hintValue;
    }

    public override PropertyDescriptorCollection GetProperties()
    {
        // Enumerate the original set of properties and create our new set with it
        PropertyDescriptorCollection originalProperties = base.GetProperties();
        List<PropertyDescriptor> newProperties = new List<PropertyDescriptor>();
        foreach (PropertyDescriptor pd in originalProperties)
        {
            if (pd.Name == this.PropertyName)
            {
                Attribute attr = new UIHintAttribute(this.HintValue);
                var newProp = TypeDescriptor.CreateProperty(typeof(object), pd, attr);
                newProperties.Add(newProp);
            }
            else
            {
                newProperties.Add(pd);
            }

        }

        // Finally return the list
        return new PropertyDescriptorCollection(newProperties.ToArray(), true);
    }

}

然后我在我的控制器中使用以下命令进行设置:

代码语言:javascript
复制
UIHintDescriptionProvider provider =
                new UIHintDescriptionProvider(TypeDescriptor.GetProvider(typeof(PageContentItem)), "Text",
                                              "wysiwyg");
            TypeDescriptor.AddProvider(provider, item);

使用TypeDescriptor函数在此对象的控制器中进行的检查表明,确实已经设置了此属性,但是它根本没有出现在我的视图中。单步执行MVC3源代码会显示所有其他属性,但不是我刚才设置的属性。

MVC3是否会在后台缓存对象类型描述,以说明这一事实?

关于在运行时将属性注入到对象实例中,还有其他建议吗?

EN

回答 1

Stack Overflow用户

发布于 2012-06-25 14:48:03

这可能是因为“时机”的原因。尝试使用自定义ModelMetadataProvider以编程方式设置模型属性属性,如“UIHint”或“DisplayName”或...看一下here

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7321452

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档