用PropertyGrid控件在运行时显示组件属性时,怎样让属性为空值的时候不显示在PropertyGrid中。能否不按控件自身提供的分类排序和字母排序,自定义PropertyGrid中各组的排序?

解决方案 »

  1.   

    [Category()]
    可以自定义属性的分类。为空不显示是不可能的,除非你自己扩展PropertyGrid控件
      

  2.   

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();        this.propertyGrid1.ToolbarVisible = false;
            this.propertyGrid1.PropertySort = PropertySort.Categorized;
            this.propertyGrid1.SelectedObject = new My() { FirstName = "ShowMe", LastName = "MeToo" };
        }
    }[TypeConverter( typeof(My.OrderedPropertyConverter) )]
    public class My
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }    private class OrderedPropertyConverter : TypeConverter
        {
            public override bool GetPropertiesSupported(ITypeDescriptorContext context)
            {
                return true;
            }
            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                List<PropertyDescriptor> result = new List<PropertyDescriptor>();
                foreach(PropertyDescriptor pd in TypeDescriptor.GetProperties(value, attributes))
                {
                    // 不显示null的属性 - 不过也就没有办法编辑了:)
                    if (pd.PropertyType.IsValueType || pd.GetValue(value) != null)
                    {
                        result.Add(pd);
                    }
                }
                PropertyDescriptorCollection pdc = new PropertyDescriptorCollection(result.ToArray());             // 自定义排序
                pdc.Sort(new string[]{"FirstName", "LastName", "Age"} );
                return pdc;
            }
        }
    }
      

  3.   

    propertyGrid.Refresh();刷新一下就可以了 - -