How to get a runtime list into a PropertyGrid?
See the question and my original answer on StackOverflowYou can override type descriptions before using types with the TypeDescriptor class, passing it a custom type descriptor.
It's a bit convoluted and you want to make sure you scan types and properties before you configure type descriptor or you may run into stack overflow. (TypeDescriptor.GetProperties
has a noCustomTypeDesc
parameter but it seems ineffective with my .NET 9 tests...)
Here is a sample TypeDescriptionProvider that should do what you need from assembly B (.NET Core code):
Data obj = new Data();
// configure a custom type descriptor for the Data type
var td = new DataDescriptor();
TypeDescriptor.AddProvider(new DescriptionProvider(td), typeof(Data));
propertyGrid1.SelectedObject = obj;
Sample classes:
public class DescriptionProvider(ICustomTypeDescriptor descriptor) : TypeDescriptionProvider
{
public override ICustomTypeDescriptor? GetTypeDescriptor([DynamicallyAccessedMembers((DynamicallyAccessedMemberTypes)(-1))] Type objectType, object? instance)
=> descriptor;
}
public class DataDescriptor : CustomTypeDescriptor
{
public DataDescriptor()
{
var properties = TypeDescriptor.GetProperties(typeof(Data));
var list = new List<PropertyDescriptor>();
foreach (PropertyDescriptor property in properties)
{
if (property.Name == "Text")
{
list.Add(TypeDescriptor.CreateProperty(typeof(Data), property, new TypeConverterAttribute(typeof(CustomConverter))));
}
else
{
list.Add(property);
}
}
_properties = new PropertyDescriptorCollection([.. list]);
}
private PropertyDescriptorCollection _properties;
public override PropertyDescriptorCollection GetProperties(Attribute[]? attributes) => _properties;
}
public class CustomConverter : TypeConverter
{
public override bool GetStandardValuesSupported(ITypeDescriptorContext? context)
=> true;
public override StandardValuesCollection? GetStandardValues(ITypeDescriptorContext? context)
=> new(new List<string> { "hello", "world" });
}