2011-01-07 43 views
2

我有類,如:如何控制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(); 

我希望的「內部」的屬性顯示爲「前」,「後」,屬性網格似乎把他們按字母順序,因此它們顯示爲「之後「,」之前「

回答

3

我不喜歡這樣的解決方案,但它似乎工作:

與所有的「排序」創建一個子類「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}  
}  
1

使用PropertyGrid.PropertySort屬性可以更改屬性的排序。可能的值如下...

NoSort 
Alphabetical 
Categorized 
CategorizedAlphabetical 

我建議NOSORT爲你適當的值。

+0

這將意味着壓倒一切的行爲也一樣,如果你可以從該屬性繼承。 – leppie 2011-01-07 10:08:39

1

我知道這樣一個老問題,但這種解決方案比接受一個簡單的:

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; } 
}