前些天,由于在项目中需要用到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. js判断css动画效果是否结束

    <!-- css样式 --> <style> .test{ width: 100px; height: 100px; transition: all 5s; backgroun ...

  2. Android开发:《Gradle Recipes for Android》阅读笔记(翻译)4.5——使用Android Libraries

    问题: 你想要在app当中增加新的library模块 解决方案: 使用library插件,增加一个library模块作为依赖. 讨论: 不可以通过使用java库给app增加许多功能,通常是使用jar包 ...

  3. Android中流式布局和热门标签

    1.流式布局特点.应用场景.2.自定义ViewGroup (1)onMeasure:测量子View的宽和高,设置自己的宽和高. (2)onLayout:设置子View的位置. onMeasure:根据 ...

  4. CNBlog客户端--第一阶段记录

    开始 五一小长假由于没有出去玩,所以我就用来继续写我的 CNBlog Android 客户端!首先呢!先上图!让大家看看,我做到哪儿了!! 不知道大家看了是什么感觉哈!有意见请评论哦!! 完成度以及遇 ...

  5. zoj3659(经典并查集)

    这种思想很经典. 从最小的边选择,那么可以知道的是,在除去这条边的另外两个联通块,选其中一块中的点做为源点到另一块所得到的费用和. 如果你已经知道了这两个联通块内部选一个点时的最大费用和.那么这题就可 ...

  6. spring 和 struts 整合遇到的问题(学习中)

    一大早就报错 org.hibernate.TransactionException: Transaction not successfully started at org.hibernate.eng ...

  7. (转)SPDY

    SPDY:Google开发的基于传输控制协议(TCP)的应用层协议,目前已经被用于Google Chrome浏览器中来访问Google的SSL加密服务.SPDY并不是一种用于替代HTTP的协议,而是对 ...

  8. 160815、mysql主从复制/读写分离

    mysql主从复制主服务器IP:192.168.99.10从服务器IP:192.168.99.20(一)安装mysql(主从服务器操作相同)yum -y install gcc gcc-c++ ncu ...

  9. Access 2010 VBA 读取 表中的数据

    Option Compare Database Private Sub Command0_Click() Dim db Dim rs As Recordset Dim str As String Se ...

  10. 你不知道的Javascript(上卷)读书笔记之四 ---- 提升、this

    1. 提升 使用var声明的变量声明和函数的声明(函数表达式不会)会被提升至所在函数作用域顶部 a. 从编译器角度出发 回忆一下, 中关于编译器的内容,引擎会在解释 JavaScript 代码之前首先 ...