How can I customize category sorting on a PropertyGrid?

前端 未结 4 629
深忆病人
深忆病人 2021-02-07 01:49

How can I customize the sorting of categories in a PropertyGrid?

If I set either of the following...

propertyGrid.PropertySort = PropertySor         


        
4条回答
  •  一个人的身影
    2021-02-07 02:17

    Like @Marc Gravel said in his answer, there's nothing in the framework that allows this behaviour. Any solution will be a hack. With that said, you can use the solution suggested by @Shahab in his answer as a work-around but that doesn't really indicate your intention to anyone maintaining your code. So I think the best you can do is create a custom Attribute which inherits from CategoryAttribute to handle the process for you:

    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))
        {
        }
    }
    

    Then you can use it as such

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

    Just make sure you set the PropertyGrid's UseCompatibletextRendering property to true to strip out the non-printable characters for you and the PropertySort set to Categorized or CategorizedAlphabetical and you should be good to go.

提交回复
热议问题