【问题标题】:How to show the "Value" property of an object in a PropertyGrid如何在 PropertyGrid 中显示对象的“值”属性
【发布时间】:2012-03-11 13:33:09
【问题描述】:

我正在尝试为具有事件系统的游戏制作一个编辑器,该编辑器具有事件的基类,然后每种类型的另一个类实际上可以完成所有工作。

所以,我有一个显示在 PropertyGrid 中的 BaseEvent 列表,作为列表,集合编辑器打开。我准备了一个 TypeConverter,所以我有一个包含所有派生类的下拉列表,显示在“Value”属性中。

一切正常,派生类的属性显示为“Value”的子级,但只要我想显示 BaseEvent 中的属性,“Value”属性就会消失,子级会出现在根部,所以我无法更改事件的类型。

有没有办法让“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
}

【问题讨论】:

  • 我找到了一种解决方法,它包括覆盖所有子类中的 BaseProperty,例如“public new bool BaseProperty { get { return base.BaseProperty; } }”,虽然它不是很优雅......

标签: c# winforms propertygrid


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多