首先我们定义的资源类Human:
public
class
Human
{
public string Name { get ; set ; }
public Human Child { get ; set ; }
}
{
public string Name { get ; set ; }
public Human Child { get ; set ; }
}
在WPF的xaml文件中引用该资源,
<Window.Resources>
<local:Human x:Key="human" Name="Tom" Child="ChildTom"></local:Human>
</Window.Resources>
<local:Human x:Key="human" Name="Tom" Child="ChildTom"></local:Human>
</Window.Resources>
当我们使用该资源
Human h
=
this
.FindResource(
"
human
"
)
as
Human;
if (h != null )
{
MessageBox.Show(h.Child.Name);
}
if (h != null )
{
MessageBox.Show(h.Child.Name);
}
因为这时Human的Child属性不是字符串类型,无法直接使用字符串给Child赋值,程序运行会出现如下的错误:
这时我们可以通过一些手段将Child的属性智能的转化为Human的Name属性,我们可以定义一个继承自TypeConverter类的转化类,并且重写ConvertFrom方法。
public class NameToHumanTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string Name = value.ToString();
Human child = new Human();
child.Name = Name;
return child;
}
}
这里的object value值就是从xaml里传过来的值,这时我们再将NameToHumanTypeConverter以特性的形式附加到Human上,
[TypeConverterAttribute(
typeof
(NameToHumanTypeConverter))]
public class Human
{
public string Name { get ; set ; }
public Human Child { get ; set ; }
}
public class Human
{
public string Name { get ; set ; }
public Human Child { get ; set ; }
}
好了,运行程序如下图所示,完成对WPF中将字符串值赋值给其他类型的属性