zoukankan      html  css  js  c++  java
  • 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;
            }
        }
  • 相关阅读:
    GB2312 字符集
    Excel导入
    Excel导出
    解决文件下载在火狐浏览器出现中文文件名乱码的方法
    Struts2将图片输出到页面
    jsp页面中日期的格式化
    java正则表达式笔记
    利用git将项目上传到github
    Java中枚举的写法和用法
    自定义JQuery插件
  • 原文地址:https://www.cnblogs.com/DoNetCoder/p/4374981.html
Copyright © 2011-2022 走看看