关于PropertyGrid控件的排序问题

时间:2023-03-09 02:50:38
关于PropertyGrid控件的排序问题

前些天,由于在项目中需要用到PropertyGrid这个控件,展现其所在控件的某些属性,由于有些控件的属性较多,不易浏览,而且PropertyGrid的排序默认的按照字母的顺序排列的,这样导致在在某些属性想要排在第一位非常不方便,于是我总结了网友们的一些思路,自己便解决呢!现在来说说解决思路:

1.首先为PropertyGrid添加SelectedObjectsChanged事件!

  private void propertyGrid_flow_SelectedObjectsChanged(object sender, EventArgs e)
{
propertyGrid_flow.Tag = propertyGrid_flow.PropertySort;
propertyGrid_flow.PropertySort = PropertySort.CategorizedAlphabetical;
propertyGrid_flow.Paint += new PaintEventHandler(propertyGrid_flow_Paint);
}

2.为PropertyGrid添加Paint事件! 这其中就是最核心的代码,就是按照propertyGrid默认属性排序!

  var categorysinfo = propertyGrid_flow.SelectedObject.GetType().GetField("categorys", BindingFlags.NonPublic | BindingFlags.Instance);
if (categorysinfo != null)
{
var categorys = categorysinfo.GetValue(propertyGrid_flow.SelectedObject) as List<String>;
propertyGrid_flow.CollapseAllGridItems();
GridItemCollection currentPropEntries = propertyGrid_flow.GetType().GetField("currentPropEntries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(propertyGrid_flow) as GridItemCollection;
var newarray = currentPropEntries.Cast<GridItem>().OrderBy((t) => categorys.IndexOf(t.Label)).ToArray();
currentPropEntries.GetType().GetField("entries", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(currentPropEntries, newarray);
propertyGrid_flow.ExpandAllGridItems();
propertyGrid_flow.PropertySort = (PropertySort)propertyGrid_flow.Tag;
}
propertyGrid_flow.Paint -= new PaintEventHandler(propertyGrid_flow_Paint);

3.在其中可以看到有个“categorys”变量,其中是是在propertyGrid的属性中命名:
 [TypeConverter(typeof(PropertySorter))]

public class UctlNodeStepProperty : PropertyGird
    {
        private List<string> categorys = new List<string>(){ "A", "B", "C", "D" };

}

4. 罗列propertyGrid的属性:

 private string _a1="";
private string _a2="";
private string _a3="";
private string _b1="";
private string _c1="";
private string _d1=""; [Browsable(true), Category("A"), ShowChinese("描述"),PropertyOrder()]
public string A1
{
get { return _a1; }
set { _a1 = value; }
}
[Browsable(true), Category("A"), ShowChinese("描述"),PropertyOrder()]
public string A2
{
get { return _a2; }
set { _a2 = value; }
}
[Browsable(true), Category("A"), ShowChinese("描述"),PropertyOrder()]
public string A3
{
get { return _a3; }
set { _a3 = value; }
}
[Browsable(true), Category("B"), ShowChinese("描述")]
public string B1
{
get { return _b1; }
set { _b1 = value; }
}
[Browsable(true), Category("C"), ShowChinese("描述")]
public string C1
{
get { return _c1; }
set { _c1 = value; }
}
[Browsable(true), Category("D"), ShowChinese("描述")]
public string D1
{
get { return _d1; }
set { _d1 = value; }
}

5.我想大家也看到了其中的代码,其中有个属性“PropertyOrder”,下面就是PropertyOtder类的代码:

 public class PropertySorter : ExpandableObjectConverter
{
#region Methods
public override bool GetPropertiesSupported(ITypeDescriptorContext context)
{
return true;
} public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
//
// This override returns a list of properties in order
//
PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(value, attributes);
ArrayList orderedProperties = new ArrayList();
foreach (PropertyDescriptor pd in pdc)
{
Attribute attribute = pd.Attributes[typeof(PropertyOrderAttribute)];
if (attribute != null)
{
//
// If the attribute is found, then create an pair object to hold it
//
PropertyOrderAttribute poa = (PropertyOrderAttribute)attribute;
orderedProperties.Add(new PropertyOrderPair(pd.Name,poa.Order));
}
else
{
//
// If no order attribute is specifed then given it an order of 0
//
orderedProperties.Add(new PropertyOrderPair(pd.Name,));
}
}
//
// Perform the actual order using the value PropertyOrderPair classes
// implementation of IComparable to sort
//
orderedProperties.Sort(); //
// Build a string list of the ordered names
//
ArrayList propertyNames = new ArrayList();
foreach (PropertyOrderPair pop in orderedProperties)
{
propertyNames.Add(pop.Name);
}
//
// Pass in the ordered list for the PropertyDescriptorCollection to sort by
//
return pdc.Sort((string[])propertyNames.ToArray(typeof(string)));
}
#endregion
} #region Helper Class - PropertyOrderAttribute
[AttributeUsage(AttributeTargets.Property)]
public class PropertyOrderAttribute : Attribute
{
//
// Simple attribute to allow the order of a property to be specified
//
private int _order;
public PropertyOrderAttribute(int order)
{
_order = order;
} public int Order
{
get
{
return _order;
}
}
}
#endregion #region Helper Class - PropertyOrderPair
public class PropertyOrderPair : IComparable
{
private int _order;
private string _name;
public string Name
{
get
{
return _name;
}
} public PropertyOrderPair(string name, int order)
{
_order = order;
_name = name;
} public int CompareTo(object obj)
{
//
// Sort the pair objects by ordering by order value
// Equal values get the same rank
//
int otherOrder = ((PropertyOrderPair)obj)._order;
if (otherOrder == _order)
{
//
// If order not specified, sort by name
//
string otherName = ((PropertyOrderPair)obj)._name;
return string.Compare(_name,otherName);
}
else if (otherOrder > _order)
{
return -;
}
return ;
}
}
#endregion

6.如果想隐藏Font这样的属性的一些英文属性,仅保留中文属性的话:(因为按照上面的步骤,你会发现,像Font这样的属性会同时包含中文和因为的属性,发现英文的会有点多余)

public class HideFontSubPropConverter : FontConverter
        {
            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                return new PropertyDescriptorCollection(null);
            }
        }

/// <summary>
        /// string不展开
        /// </summary>
        public class HideStringSubPropConverter : StringConverter
        {
            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                return new PropertyDescriptorCollection(null);
            }
        }
        /// <summary>
        /// size不展开
        /// </summary>
        public class HideSizeSubPropConverter : SizeConverter
        {
            public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
            {
                return new PropertyDescriptorCollection(null); ;
            }
        }

相关文章