2012-03-11 33 views
1

我試圖爲具有事件系統的遊戲編寫一個事件的基類,然後爲每種類別創建另一個類做所有的事情。如何在PropertyGrid中顯示對象的「Value」屬性

所以,我有一個BaseEvent列表,它顯示在一個PropertyGrid中,作爲一個列表,集合編輯器打開。我準備了一個TypeConverter,所以我有一個下拉式的所有派生類,它顯示在「Value」屬性中。

一切都好,來自派生類的屬性顯示爲「值」的子項,但只要我想從BaseEvent顯示屬性,「值」屬性消失,並且子項出現在根目錄下,米無法改變事件的類型。

有沒有辦法讓「Value」屬性與BaseEvent屬性同時出現?

//This allows to get a dropdown for the derived classes 
public class EventTypeConverter : ExpandableObjectConverter 
{ 
    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) 
    { 
     return new StandardValuesCollection(GetAvailableTypes()); 
    } 

    /* 
    ... 
    */ 
} 

[TypeConverter(typeof(EventTypeConverter))] 
public abstract class BaseEvent 
{ 
    public bool BaseProperty; //{ get; set; } If I set this as a property, "Value" disappears 
} 

public class SomeEvent : BaseEvent 
{ 
    public bool SomeOtherProperty { get; set; } 
} 

//The object selected in the PropertyGrid is of this type 
public class EventManager 
{ 
    public List<BaseEvent> Events { get; set; } //The list that opens the collection editor 
} 
+0

我發現其中包括在所有兒童類,如重寫BaseProperty一種變通方法「公共新的bool BaseProperty {得到{返回base.BaseProperty;}}「,雖然它不是很優雅... – Osguima3 2012-03-14 21:58:54

回答

1

最後我找到了一種方法來解決這個問題:通過的GetProperties方法,和一個自定義的PropertyDescriptor:

public override PropertyDescriptorCollection GetProperties(ITypeDescriptorContext context, object value, Attribute[] attributes) 
{ 
    //Get the base collection of properties 
    PropertyDescriptorCollection basePdc = base.GetProperties(context, value, attributes); 

    //Create a modifiable copy 
    PropertyDescriptorCollection pdc = new PropertyDesctiptorCollection(null); 
    foreach (PropertyDescriptor descriptor in basePdc) 
     pdc.Add(descriptor); 

    //Probably redundant check to see if the value is of a correct type 
    if (value is BaseEvent) 
     pdc.Add(new FieldDescriptor(typeof(BaseEvent), "BaseProperty")); 
    return pdc; 
} 

public class FieldDescriptor : SimplePropertyDescriptor 
{ 
    //Saves the information of the field we add 
    FieldInfo field; 

    public FieldDescriptor(Type componentType, string propertyName) 
     : base(componentType, propertyName, componentType.GetField(propertyName, BindingFlags.Instance | BindingFlags.NonPublic).FieldType) 
    { 
     field = componentType.GetField(propertyName, BindingFlags.Instance | BindingFlags.NonPublic); 
    } 

    public override object GetValue(object component) 
    { 
     return field.GetValue(component); 
    } 

    public override void SetValue(object component, object value) 
    { 
     field.SetValue(component, value); 
    } 
} 
相關問題