TypeConverter使用

如下代码,

<Window.Resources>

  <local:Human x:Key="human" Name="Tester1" Child="ChildOfTester1"/>

</Window.Resources>

class Human

{

  public string Name{get;set;}

  public Human Child{get;set;}

}

为了让以上代码工作,则必须提供一个类型转换, 从string转到Human。

步骤如下,

1. 定义StringToHumanConverter : TypeConverter, 重写其ConvertFrom方法,

public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
return new Human(value as string);
}

return base.ConvertFrom(context, culture, value);
}

2. 附加到Human类,

[TypeConverter(typeof(StringToHumanConverter))]
class Human

Done.

原文地址:https://www.cnblogs.com/bdbw2012/p/3848627.html