当我绑定(bind)这个对象时
public class MyObject
{
public AgeWrapper Age
{
get;
set;
}
}
public class AgeWrapper
{
public int Age
{
get;
set;
}
}
对于属性网格,属性网格的值部分显示的是 AgeWrapper 的类名,但是 AgeWrapper.Age 的值。
是否有办法在属性网格中显示复合对象的值(在本例中为 AgeWrapper.Age),而不是该复合对象的类名?
最佳答案
您需要创建一个类型转换器,然后使用属性将其应用到 AgeWrapper 类。然后属性网格将使用该类型转换器来显示要显示的字符串。创建一个像这样的类型转换器...
public class AgeWrapperConverter : ExpandableObjectConverter
{
public override bool CanConvertTo(ITypeDescriptorContext context,
Type destinationType)
{
// Can always convert to a string representation
if (destinationType == typeof(string))
return true;
// Let base class do standard processing
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value,
Type destinationType)
{
// Can always convert to a string representation
if (destinationType == typeof(string))
{
AgeWrapper wrapper = (AgeWrapper)value;
return "Age is " + wrapper.Age.ToString();
}
// Let base class attempt other conversions
return base.ConvertTo(context, culture, value, destinationType);
}
}
请注意,它继承自 ExpandableObjectConverter。这是因为 AgeWrapper 类有一个名为 AgeWrapper.Age 的子属性,需要通过网格中 AgeWrapper 条目旁边的 + 按钮来公开该属性。如果您的类没有任何您想要公开的子属性,则可以从 TypeConverter 继承。现在将此转换器应用到您的类中...
[TypeConverter(typeof(AgeWrapperConverter))]
public class AgeWrapper
关于c# - 复合对象上的属性网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/241887/