[英]Expendable complex types inside complex types in any collection (Property grid)
Hello I want to have a expandable collection of complex types which are inside of other complex type. 您好,我想在其他复杂类型中包含一个复杂类型的可扩展集合。 How I want to do this:
我要如何做:
private static void SetExpandableAttrForType(Type type)
{
var props = type.GetProperties();
foreach (var prop in props.Where(x =>!x.PropertyType.IsSimpleType()&& x.CanWrite))
{
SetExpandableAttrForType(prop.PropertyType);
}
TypeDescriptor.AddAttributes(type, new TypeConverterAttribute(typeof (ExpandableObjectConverter)));
}
and then 接着
SetExpandableAttrForType(arrayInstance.GetType().GetElementType());
Test model: 测试模型:
public class Class1
{
public Class2 Class2Inclass1 { get; set; }
public Class2[] Class2Array { get; set; }
}
public class Class2
{
public Class3 Class3Inclass2 { get; set; }
public string Class2String { get; set; }
public string Class2String2 { get; set; }
}
public class Class3
{
public Class4 Class4Inclass3 { get; set; }
public string Class3String { get; set; }
public int Class3Int { get; set; }
}
public class Class4
{
public int Class4Int { get; set; }
public DateTime Class4Datetime { get; set; }
}
It works fine for types but not for collection of types. 它适用于类型,但不适用于类型集合。
The great thing about programming is this, when u tell somebody about the problem, often you start to look at it from another angle. 关于编程的伟大之处在于,当您向某人介绍该问题时,通常您会从另一个角度来看待它。 The problem was that I need instance of this nested complex type.
问题是我需要这种嵌套的复杂类型的实例。 CellValueChanged event give me type and then I just need to create instance of it.
CellValueChanged事件为我提供类型,然后只需要创建它的实例即可。
private void propertyGridControl1_CellValueChanged(object sender, CellValueChangedEventArgs e)
{
var changedObject = e.Value;
if (changedObject != null)
{
if (changedObject.GetType().IsArray || changedObject.GetType().IsGenericList())
{
var collectionItems = changedObject as IEnumerable;
if (collectionItems != null)
foreach (var item in collectionItems)
{
SetValueOfCollectionComplexObject(item);
}
}
}
}
public void SetValueOfCollectionComplexObject(object item)
{
var complexProps = item.GetType().GetProperties().Where(x => !x.PropertyType.IsSimpleType());
foreach (var prop in complexProps)
{
if (prop.GetValue(item) == null)
{
prop.SetValue(item, Activator.CreateInstance(prop.PropertyType));
SetValueOfCollectionComplexObject(prop.GetValue(item));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.