要使网格中的“B”类值正确显示,请覆盖返回Title属性的方法ToString。
然后,您可以为“B”类中创建一个TypeConvertor所以网格知道如何串单元格的值转换为“B”类的类型,即
public class BStringConvertor : TypeConverter
{
public BStringConvertor()
: base()
{
}
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
// Allow conversion from a String type
if (sourceType == typeof(string))
return true;
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
// If the source value is a String, convert it to the "B" class type
if (value is string)
{
B item = new B();
item.Title = value.ToString();
return item;
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType)
{
// If the destination type is a String, convert the "B" class to a string
if (destinationType == typeof(string))
return value.ToString();
return base.ConvertTo(context, culture, value, destinationType);
}
}
然后你可以转换申请您的“A”类的“B”级属性,即
public class A
{
public string Title { get; set; }
[TypeConverter(typeof(BStringConvertor))]
public B BField { get; set; }
}
public class B
{
public string Title { get; set; }
public override string ToString()
{
return this.Title;
}
}
您能否为第二个示例定义“它不工作”?我希望它能起作用。 – 2010-08-10 14:54:21
谢谢大家。我在我的代码中发现了问题。对于修复问题,我决定使用例如“public String BField_Name ...”这一行。但转换器也是非常好的主意。 – oivoodoo 2010-08-19 11:08:37