WPF TypeConverter用法 拓荒者

WPF的流行,或者说是XAML的流行已经不可阻挡了。所以学习一些WPF的知识是非常有必要的。

关于TypeConverter,其实是一个将XAML属性值(string字符串)转换为对象的转换器。

要实现这个转换器,需要我们首先定义一个继承自TypeConverter类的转换类。

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

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

这个类是将一个XAML属性值转换为程序中的Human对象,Human的定义如下:

    public class Human
    {
        public string Name { get; set; }
        public Human Child { get; set; }
    }

当定义好转换器以后,我们还需要通过为Human添加特性的形式将转换器和被转换的类关联起来,修改后的Human代码如下(改动的地方已标红):

    [TypeConverter(typeof(StringToHumanTypeConverter))]
    public class Human
    {
        public string Name { get; set; }
        public Human Child { get; set; }
    }

通过这样定义以后,我们可以直接在XAML中为Human附加字符串值。

    <Window.Resources>
        <local:Human x:Key="human" Name="Tom" Child="ABC"></local:Human>
    </Window.Resources>

注意:关于local前缀,直接写上去是会出错的。需要在Window中定义:xmlns:local="clr-namespace:SampleTypeConverter"

我们在程序中可以通过查找资源来找到human对象,并访问其Child属性:

    Human human = (Human)this.FindResource("human");
    MessageBox.Show(human.Child.Name);

以上代码参考自《深入浅出WPF》,仅作学习笔记。

原文地址:https://www.cnblogs.com/youring2/p/2795586.html