开发者

how to make fields editable at runtime

开发者 https://www.devze.com 2023-03-09 03:59 出处:网络
Is it possible to apply EditableAttribute at runtime? I want to make some properties editabl开发者_运维问答e only when the user has some role. Unfortunately EdiatbleAttribute is sealed. I can try to a

Is it possible to apply EditableAttribute at runtime? I want to make some properties editabl开发者_运维问答e only when the user has some role. Unfortunately EdiatbleAttribute is sealed. I can try to apply it at runtime by reflection but maybe there's more proper way to do this. Thanks for any advices.

Best regards


There is a hack available at: How to Set Attribute Value at Runtime-- and How to Work around a Silly Bug

private void SetPropertyGrid() 
{ 
     PropertyDescriptor descriptor = TypeDescriptor.GetProperties(typeof(Student))["Address"];
     ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
     FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
        isReadOnly.SetValue(attrib,true);

     propertyGrid1.SelectedObject = new Student();  
}

I was able to this code to change the ReadOnly attribute value of the property. The statement propertyGrid1.SelectedObject = new Student(); can be replaced by propertyGrid1.SelectedObject = myStudent i.e. you can modify the properties of an existing object.

Also, have a look at a similar question: Change Attribute's parameter at runtime


I think a good option is to create an extension helper for the control you need to use (TextBox etc) and if the IsReadOnly property is true (Editable(false)) then generate a disabled textbox.

0

精彩评论

暂无评论...
验证码 换一张
取 消