如何在PropertyGrid上自定义类别排序?

Gar*_*idd 20 .net propertygrid winforms

如何自定义类别的排序PropertyGrid

如果我设置以下任一项...

propertyGrid.PropertySort = PropertySort.Categorized;
propertyGrid.PropertySort = PropertySort.CategorizedAlphabetical;
Run Code Online (Sandbox Code Playgroud)

...然后类别将按字母顺序排列.("按字母顺序"似乎适用于每个类别中的属性.)如果我使用PropertySort.NoSort,我会失去分类.

我在我的填充PropertyGridSelectObject,这是很容易的:

this.propertyGrid1.SelectedObject = options;
Run Code Online (Sandbox Code Playgroud)

options 是具有适当装饰属性的类的实例:

    [CategoryAttribute("Category Title"),
    DisplayName("Property Name"),
    Browsable(true),
    ReadOnly(false),
    BindableAttribute(true),
    DesignOnly(false),
    DescriptionAttribute("...")]
    public bool PropertyName {
        get {
            // ...
        }

        set {
            // ...
            this.OnPropertyChanged("PropertyName");
        }
    }
Run Code Online (Sandbox Code Playgroud)

我在六个类别中有几十个属性.

有没有什么方法可以调整类别排序顺序,同时保持我的易用性SelectedObject

小智 21

我认为这个链接很有用 http://bytes.com/groups/net-c/21​​4456-q-ordering-sorting-category-text-propertygrid

我不相信有办法做到这一点.我能找到的唯一表明你可以做到这一点的是PropertySort属性.如果将其设置为none,则表示属性按照从类型描述符接收的顺序显示.您可能能够在对象和propertygrid之间创建代理类型描述符,然后不仅会以正确的顺序返回属性,而且还会按照您希望的顺序返回包含类别的属性...

  • 最后的伎俩是纯粹的邪恶天才;-令人讨厌,但如果它完成了工作...... (9认同)
  • 我不知道你们是否看过@JoelB的答案(下图),但基本上是这个但是类固醇.就使用和可维护性而言,更不用说hacky了.:-) (5认同)
  • 与能够执行此操作的好处相比,工具提示的问题很小.很好找. (2认同)

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))
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以这样使用它

[CustomSortedCategory("Z Category",1,2)]
public string ZProperty {set;get;}
[CustomSortedCategory("A Category",2,2)]
public string AProperty {set;get;}
Run Code Online (Sandbox Code Playgroud)

只要确保你设置PropertyGridUseCompatibletextRendering属性true为你去除不可打印的字符和PropertySort设置为Categorized或者CategorizedAlphabetical你应该好好去.


Mar*_*ell 4

如果您的意思是希望以特定(非字母顺序)方式对类别进行排序,那么不行 - 我认为您不能这样做。您可能想尝试VisualHint - 我希望它确实有这个(因为您可以抓住更多的控制权)。