如何控制winforms属性网格中ExpandableObject属性的顺序?
问题描述:
我有类,如:如何控制winforms属性网格中ExpandableObject属性的顺序?
[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();
我希望的“内部”的属性显示为“前”,“后”,属性网格似乎把他们按字母顺序,因此它们显示为“之后“,”之前“
答
我不喜欢这样的解决方案,但它似乎工作:
与所有的“排序”创建一个子类“PropertyDescriptorCollection”的方法重载只是回到“本”。所以每当属性网格调用排序来改变属性的顺序时,什么都不会发生。
创建一个“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}
}
答
使用PropertyGrid.PropertySort属性可以更改属性的排序。可能的值如下...
NoSort
Alphabetical
Categorized
CategorizedAlphabetical
我建议NOSORT为你适当的值。
答
我知道这样一个老问题,但这种解决方案比接受一个简单的:
public class MyExpandableObjectConverter : ExpandableObjectConverter
{
public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes)
{
return TypeDescriptor.GetProperties(typeof(Inner), attributes).Sort(new[] { "Before", "After" });
}
}
[TypeConverterAttribute(typeof(MyExpandableObjectConverter))]
public class Inner
{
public string Before { get; set; }
public string After { get; set; }
}
这将意味着压倒一切的行为也一样,如果你可以从该属性继承。 – leppie 2011-01-07 10:08:39