WPF:使用TypeConverter

所谓TypeConverter就是类型转换器,支持两种类型之间相互转换

你可以重写转换逻辑,只要你清楚转换的协议,就可以实现类型互转。

定义一个Person类型,具有一个int类型的Age属性:

public class Person

    {

        public int Age

        {

            get;

            set;

        }

    }


在XAML中添加一个Person的资源:

    <Window.Resources>

        <local:Person x:Key="person"></local:Person>

    </Window.Resources>

本来可以像这样初始化一个Person对象:

    <Window.Resources>

        <local:Person x:Key="person" Age="123"></local:Person>

    </Window.Resources>

但是现在由于要引入TypeConverter,假设我想像下面这样初始化Person对象怎么办:

    <Window.Resources>

        <local:Person x:Key="person">123</local:Person>

    </Window.Resources>

这就要用到TypeConverter,首先我们定义自己的Converter,继承自TypeConverter,然后重写TypeConverter的转换逻辑:

    public class StringToPersonConverter:TypeConverter

    {

        /// <summary>

        /// 从String转换为Person

        /// </summary>

        /// <param name="context"></param>

        /// <param name="culture"></param>

        /// <param name="value"></param>

        /// <returns></returns>

        public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)

        {

            int age;

            if (int.TryParse(value.ToString(), out age))

            {

                return new Person

                {

                    Age = age

                };

            }



            return null;

        }

    }

然后给Person类加上TypeConverter特性,让编译器知道当无法通过正常的方式初始化Person时,可以找StringToPersonConverter寻求帮助:

    [TypeConverter(typeof(StringToPersonConverter))]

    public class Person

    {

        public int Age

        {

            get;

            set;

        }

    }

 

你可能感兴趣的:(Converter)