Jecho

导航

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.

posted on 2014-07-16 14:31  Jecho  阅读(342)  评论(0编辑  收藏  举报