PropertyDescriptorCollection - Object does not match target type

532 Views Asked by At

I have a PropertyGrid with a SelectedObject of an object of type class1.

I am implementing the ICustomTypeDescriptor interface for the class1 object, and I am getting a PropertyDescriptorCollection from another object class2, and needing to display the class2 PropertyDescriptors in a PropertyGrid as well as the class1 PropertyDescriptors.

I am getting the following error displayed in the PropertyGrid for the class2 PropertyDescriptors:

Object does not match target type.

Here is my code that works without the class2 PropertyDescriptors:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(this);
    var propertyDescriptors = new List<PropertyDescriptor>();
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(propertyDescriptorCollection[i]);
    }
    return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
}

Here is the code that I am working on:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(this);
    var propertyDescriptors = new List<PropertyDescriptor>();
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(propertyDescriptorCollection[i]);
    }
    var class2PropertyDescriptorCollection = TypeDescriptor.GetProperties(class2);
    for (int i = 0; i < class2PropertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(class2PropertyDescriptorCollection[i]);
    }
    return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
}

How can I display the PropertyDescriptors from class2, when the PropertyDescriptors from class1 are displayed in a PropertyGrid?

1

There are 1 best solutions below

0
Dustin On

You have declared propertyDescriptorCollection as type PropertyDescriptorCollection, but have used var for the class2PropertyDescriptorCollection. What if you tried the following:

public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
{
    PropertyDescriptorCollection propertyDescriptorCollection = TypeDescriptor.GetProperties(this);
    var propertyDescriptors = new List<PropertyDescriptor>();
    for (int i = 0; i < propertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(propertyDescriptorCollection[i]);
    }
    PropertyDescriptorCollection class2PropertyDescriptorCollection = TypeDescriptor.GetProperties(class2);
    for (int i = 0; i < class2PropertyDescriptorCollection.Count; i++)
    {
        propertyDescriptors.Add(class2PropertyDescriptorCollection[i]);
    }
    return new PropertyDescriptorCollection(propertyDescriptors.ToArray());
}