using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ControlLibrary;
using System.Reflection;
namespace WindowsFormsMocking
{
public partial class Form1 : Form
{
private ContactInfo contactInfo = null;
public Form1()
{
InitializeComponent();
contactInfo = new ContactInfo();
contactInfo.ChildContact = new ContactInfo();
propertyGrid1.SelectedObject = contactInfo;
}
private void button1_Click(object sender, EventArgs e)
{
ContactInfo.SetMobileEdit(contactInfo, "Mobile", false);
propertyGrid1.Refresh();
}
}
[TypeConverter(typeof(ExpandableObjectConverter))]
public class ContactInfo
{
[ReadOnly(false)]
[Category("Contact Info")]
public string Mobile { get; set; }
[Category("Contact Info")]
public string Name { get; set; }
[Category("Child contact Info")]
public ContactInfo ChildContact { get; set; }
static public void SetMobileEdit(object instance, string property, bool allowEdit)
{
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(instance.GetType())[property];
ReadOnlyAttribute attrib = (ReadOnlyAttribute)descriptor.Attributes[typeof(ReadOnlyAttribute)];
FieldInfo isReadOnly = attrib.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
// the Mobile property becomes Readonly for both contactInfo and souContactInfo
// unfortunatly, I'm not finding the way to modified only contactInfo instance
isReadOnly.SetValue(attrib, !allowEdit);
}
}
}
|