Gar*_*idd 20 .net propertygrid winforms
如何自定义类别的排序PropertyGrid?
如果我设置以下任一项...
propertyGrid.PropertySort = PropertySort.Categorized;
propertyGrid.PropertySort = PropertySort.CategorizedAlphabetical;
...然后类别将按字母顺序排列.("按字母顺序"似乎适用于每个类别中的属性.)如果我使用PropertySort.NoSort,我会失去分类.
我在我的填充PropertyGrid用SelectObject,这是很容易的:
this.propertyGrid1.SelectedObject = options;
options 是具有适当装饰属性的类的实例:
    [CategoryAttribute("Category Title"),
    DisplayName("Property Name"),
    Browsable(true),
    ReadOnly(false),
    BindableAttribute(true),
    DesignOnly(false),
    DescriptionAttribute("...")]
    public bool PropertyName {
        get {
            // ...
        }
        set {
            // ...
            this.OnPropertyChanged("PropertyName");
        }
    }
我在六个类别中有几十个属性.
有没有什么方法可以调整类别排序顺序,同时保持我的易用性SelectedObject?
小智 21
我认为这个链接很有用 http://bytes.com/groups/net-c/214456-q-ordering-sorting-category-text-propertygrid
我不相信有办法做到这一点.我能找到的唯一表明你可以做到这一点的是PropertySort属性.如果将其设置为none,则表示属性按照从类型描述符接收的顺序显示.您可能能够在对象和propertygrid之间创建代理类型描述符,然后不仅会以正确的顺序返回属性,而且还会按照您希望的顺序返回包含类别的属性...
Joe*_*l B 16
就像@Marc Gravel在他的回答中所说,框架中没有任何东西允许这种行为.任何解决方案都是黑客攻击.话虽如此,你可以使用@Shahab在他的答案中提出的解决方案作为解决方法,但这并不能真正表明你有意维护你的代码.所以我认为你能做的最好的事情就是创建一个Attribute继承自己的自定义CategoryAttribute来处理这个过程:
public class CustomSortedCategoryAttribute : CategoryAttribute
{
    private const char NonPrintableChar = '\t';
    public CustomSortedCategoryAttribute(   string category,
                                            ushort categoryPos,
                                            ushort totalCategories)
        : base(category.PadLeft(category.Length + (totalCategories - categoryPos),
                    CustomSortedCategoryAttribute.NonPrintableChar))
    {
    }
}
然后你可以这样使用它
[CustomSortedCategory("Z Category",1,2)]
public string ZProperty {set;get;}
[CustomSortedCategory("A Category",2,2)]
public string AProperty {set;get;}
只要确保你设置PropertyGrid的UseCompatibletextRendering属性true为你去除不可打印的字符和PropertySort设置为Categorized或者CategorizedAlphabetical你应该好好去.