Remove C# attribute of a property dynamically

白昼怎懂夜的黑 提交于 2019-11-27 04:40:26

You can not remove the attribute at runtime, but you can use reflection to change the ReadOnly attribute's ReadOnly private backing field to False. Making it the equivalent of [ReadOnly(false)]

See this article for details:

http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html

Edit: fixed link

I have to agree w/ Omu; you're really talking about two classes (view models) in this case, to support your two different views. Something like

CreateContactViewModel and EditContactViewModel

it's not possible at the moment to remove attributes dinamycally (at runtime)

as a suggestion you can do 2 classes: one with the attributes and one without

I followed up the suggestion by Legenden. Here is what I came up with

class ContactInfo
{
        [ReadOnly(true)]
        [Category("Contact Info")]
        public string Mobile { get; set; }

        [Category("Contact Info")]
        public string Name{ get; set; }

        public void SetMobileEdit(bool allowEdit)
        {
             PropertyDescriptor descriptor =  TypeDescriptor.GetProperties(this.GetType())["Mobile"];

             ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];

             FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);

             isReadOnly.SetValue(attrib, !allowEdit);
        }
}
Mau

The CodingLight.com blog moved to blogspot (the above link is broken). See http://codinglight.blogspot.com/2008/10/changing-attribute-parameters-at.html.

Moreover, SysAdmin's followup did not mention the [RefreshProperties(RefreshProperties.All)] attribute that seems to be necessary for an actually-working solution.

Finally, I believe that even David Morton (author of the quoted article) missed one very important thing: if the class (ContactInfo, in SysAdmin's followup example) does not have at least one property with the [ReadOnly] attribute defined at compile time, then when the "isReadOnly" FieldInfo is set to true at runtime the result is that the whole class turns read-only.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!