.netwinformsuser-controlspropertygriddesign-view

Disable Property in Design View Property Grid


I want to expose some properties in my custom control. I require to get input for three parameters that I expose as Browsable properties from the control. Based on input for one property the other two might not be required. How can I disable/hide the properties that are not required based on selection for first property?


Solution

  • Yes, with a little reflection, you can achieve this:

    public class TestControl : Control {
      private string _PropertyA = string.Empty;
      private string _PropertyB = string.Empty;
    
      [RefreshProperties(RefreshProperties.All)]
      public string PropertyA {
        get { return _PropertyA; }
        set {
          _PropertyA = value;
    
          PropertyDescriptor pd = TypeDescriptor.GetProperties(this.GetType())["PropertyB"];
          ReadOnlyAttribute ra = (ReadOnlyAttribute)pd.Attributes[typeof(ReadOnlyAttribute)];
          FieldInfo fi = ra.GetType().GetField("isReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);
          fi.SetValue(ra, _PropertyA == string.Empty);
        }
      }
    
      [RefreshProperties(RefreshProperties.All)]
      [ReadOnly(true)]
      public string PropertyB {
        get { return _PropertyB; }
        set { _PropertyB = value; }
      }
    }
    

    This will disable PropertyB whenever PropertyA is an empty string.

    Found this article at the Code Project that described this process.