一、XAML引用类
using System;
using System.Collections.Generic;using System.Linq;
using System.Text;
using System.ComponentModel; //加上这个空间
1、定义类
namespace 第一个WPF{
[TypeConverter(typeof(Converter))] 类型转换,必须有
public class Human
{
public string Name { get; set; }
public Human Child { get; set; }
}
}
2、xaml中引用
xmlns:Human="clr-namespace:第一个WPF",clr-namespace必须有
3、创建Window.Resources段
<Window.Resources>
<Human:Human x:Key="123" Child="asd"/>
</Window.Resources>
二、类型转换
从TypeConverter中派生出自己的类,并重写它的一个ConvertFrom方法。这个方法有一个参数名为value,我们要做的就是讲这个值“翻译”成合适的值赋给对象的属性。类似于int.TryParse
class Converter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
if (value is string)
{
Human h = new Human();
h.Name = value as string;
return h;
}
return base.ConvertFrom(context, culture, value);
}
}
private void btn_Click(object sender, RoutedEventArgs e)
{
Human h = (Human)this.FindResource("123");
MessageBox.Show(h.Child.Name); //human.Child是human类型,而在xaml代码中“asd”是字符串,编译器不知道如何把“asd”字符串转换为 //Human实例,所以必须实现TypeConvert
}