前些天,由于在项目中需要用到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); ;
            }
        }

关于PropertyGrid控件的排序问题的更多相关文章

  1. PropertyGrid控件由浅入深(二):基础用法

    目录 PropertyGrid控件由浅入深(一):文章大纲 PropertyGrid控件由浅入深(二):基础用法 控件的外观构成 控件的外观构成如下图所示: PropertyGrid控件包含以下几个要 ...

  2. PropertyGrid控件由浅入深(一):文章大纲

    Winform中PropertyGrid控件是一个非常好用的对象属性编辑工具,对于Key-Value形式的数据的处理也是非常的好用. 因为Property控件设计良好,在很小的空间内可以展示很多的内容 ...

  3. WinForm小白的WPF初试一:从PropertyGrid控件,输出内容到Word(上)

    学WinForm也就半年,然后转到WPF,还在熟悉中.最近拿到一个任务:从PropertyGrid控件,输出内容到Word.难点有: 一.PropertyGrid控件是WinForm控件,在WPF中并 ...

  4. C# 如何定义让PropertyGrid控件显示[...]按钮,并且点击后以下拉框形式显示自定义控件编辑属性值

    关于PropertyGrid控件的详细用法请参考文献: 1.C# PropertyGrid控件应用心得 2.C#自定义PropertyGrid属性 首先定义一个要在下拉框显示的控件: using Sy ...

  5. WinForm窗体PropertyGrid控件的使用

    使用过 Microsoft Visual Basic 或 Microsoft Visual Studio .NET的朋友,一定使用过属性浏览器来浏览.查看或编辑一个或多个对象的属性..NET 框架 P ...

  6. C# PropertyGrid控件应用心得

    何处使用 PropertyGrid 控件 在应用程序中的很多地方,您都可以使用户与 PropertyGrid 进行交互,从而获得更丰富的编辑体验.例如,某个应用程序包含多个用户可以设置的“设置”或选项 ...

  7. propertyGrid控件 z

    1.如果属性是enum类型,那么自然就是下拉的. 2.如果是你自定义的下拉数据,那么需要用到转换属性标签TypeConverter 参见: http://blog.csdn.net/luyifeini ...

  8. 自定义PropertyGrid控件【转】

    自定义PropertyGrid控件 这篇随笔其实是从别人博客上载录的.感觉很有价值,整理了一下放在了我自己的博客上,希望原作者不要介意. 可自定义PropertyGrid控件的属性.也可将属性名称显示 ...

  9. C# PropertyGrid控件应用心得 【转】

    源文 : http://blog.csdn.net/luyifeiniu/article/details/5426960 c#stringattributesobjectmicrosoftclass ...

随机推荐

  1. iOS -转载-字符串是否为空判断方法

    - (BOOL)blankString{ if (![self isKindOfClass:[NSString class]] ){ return YES; } if ([self isEqual:[ ...

  2. PDO防止sql注入的机制

    使用PDO訪问MySQL数据库时,真正的real prepared statements 默认情况下是不使用的. 为了解决问题,你必须禁用 prepared statements的仿真效果. 以下是使 ...

  3. 面试题思考:什么是 Java 的反射机制

    一.反射机制概述 Java 反射机制是在运行状态中,对于任意一个类,都能够获得这个类的所有属性和方法,对于任意一个对象都能够调用它的任意一个属性和方法.这种在运行时动态的获取信息以及动态调用对象的方法 ...

  4. ionicframework I ------------- 初体验

    ionicframework I -------------  初体验 Create hybrid mobile apps with the web technologies you love. Fr ...

  5. mysql数据库导入到oracle数据库

    首先,写一个cmd脚本 xx.cmd sqlldr username/password control=xx.ctl errors=10000000 direct=y 再写一个bat脚本xx.bat ...

  6. [hihoCoder] Trie树

    This is a application of the Trie data structure, with minor extension. The critical part in this pr ...

  7. selenium调用Firefox和Chrome需要注意的一些问题,和出现的报错selenium:expected [object undefined] undefined to be a string

    在高版本selenium下如:selenium3.4.3 1.高版本的selenium需要浏览器安装一些补丁驱动 Firefox:geckodriver 下载网址:http://download.cs ...

  8. FineReport----查询功能 的知识点

    1.设置日期控件,默认当前日期 2.默认不查询 选择参数:点击查询前不显示报表内容

  9. java.lang.IllegalStateException: Queue full

    其实异常说的很清楚 队列满了! ArrayBlockingQueue FIFO 的队列: ArrayBlockingQueue内部是通过一个Object数组和一个ReentrantLock实现的.同时 ...

  10. android studio 新建项目 界面一直停在 【“building ‘ 项目名’ gradle project info”】

    安装了android studio 之后,按照上文所述的那篇博文下载安装gradle,配置环境变量, 启动android studio,新建项目,发现还是新建不了,界面一直停在 ["buil ...