.net - 如何控制 winforms 属性网格中 ExpandableObject 属性的顺序?

标签 .net winforms propertygrid

我有这样的类(class):

[TypeConverterAttribute(typeof(ExpandableObjectConverter))]
public class Inner
{
   public string Before{get;set}
   public string After(get;set}
}

public class Outer
{
    public Inner Inner {get;set}
}

myPropertygrid.SelectedObject = new Outer();

我希望“inner”的属性显示为“Before”,“After”,属性网格似乎将它们按字母顺序排列,因此显示为“After”,“Before”

最佳答案

我不喜欢这个解决方案,但它似乎有效:

创建“PropertyDescriptorCollection”的子类,并覆盖所有“Sort”方法以返回“this”。因此,每当属性网格调用 sort 来更改属性的顺序时,都不会发生任何事情。

创建“ExpandableObjectConverter”的子类,重写“GetProperties”方法以返回“NoneSortingPropertyDescriptorCollection”的实例,其中属性的顺序正确。

使用 [TypeConverterAttribute(typeof(MyExpandableObjectConverter))] 来使用 ExpandableObjectConverter 的子类。

public class NoneSortingPropertyDescriptorCollection : PropertyDescriptorCollection
{
    public NoneSortingPropertyDescriptorCollection(PropertyDescriptor[] propertyDescriptors)
        : base(propertyDescriptors)
    {
    }

    public override PropertyDescriptorCollection Sort()
    {
        return this;
    }
    public override PropertyDescriptorCollection Sort(string[] names)
    {
        return this;
    }

    public override PropertyDescriptorCollection Sort(string[] names, System.Collections.IComparer comparer)
    {
        return this;
    }
    public override PropertyDescriptorCollection Sort(System.Collections.IComparer comparer)
    {
        return this;
    }
}

public class MyExpandableObjectConverter : ExpandableObjectConverter
{
    public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
    {
        PropertyDescriptorCollection d = base.GetProperties(context, value, attributes);

        List<PropertyDescriptor> props = new List<PropertyDescriptor>();
        props.Add(d.Find("Before", false));
        props.Add(d.Find("After", false));

        NoneSortingPropertyDescriptorCollection m = new NoneSortingPropertyDescriptorCollection(props.ToArray());
        return m;
    }
}

[TypeConverterAttribute(typeof(MyExpandableObjectConverter))]      
public class Inner      
{         
   public string Before{get;set}        
   public string After(get;set}      
}    

关于.net - 如何控制 winforms 属性网格中 ExpandableObject 属性的顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4624111/

相关文章:

c# - 如何覆盖 ToString() 方法以输出列表?

c# - 将 session 包装为属性时直接保护访问 session 的方法?

c# - 在枚举值中查找最高设置标志

c# - Reflection.Emit 的性能损失

c# - 分配 Action<T> 方法和订阅 Action<T> 事件之间的区别

c# - 如何使用 backgroundworker 更新 GUI?

c# - 通过单击或 TabControl 中的键禁用选项卡之间的切换

c# - 使用 PostSharp,无法让 Multicast 为 WinForm 控件单击处理程序工作

.net - 使用 PropertyGrid 设置 PerformanceCounter

c# - 如何防止在 PropertyGrid 中滚动刷新?