C# WPF TypeConverter

[MSDN 链接] (How to: Implement a Type Converter | Microsoft Docs
)

由MSDN可知,对于内置类型 int32 、string 等在 System.ComponentMode已有默认的转换器。

我们对于它的使用主要是用于我们自己定义的一些类型。

定义自己的类并继承TypeConverter,然后根据需要重写相应的方法。

使用 TypeConverter方法 可以在设计时和运行时使用它。

但我们也可以使用实现System.IConvertible接口的方法来做到数据转换

但实现接口的方式只能在运行时使用,也就是说设计时xaml编译器有可能报错。且只支持数据的单向转换

官方示例代码

using System;
using System.ComponentModel;
using System.Globalization;
using System.Drawing;

public class PointConverter : TypeConverter {
   // Overrides the CanConvertFrom method of TypeConverter.
   // The ITypeDescriptorContext interface provides the context for the
   // conversion. Typically, this interface is used at design time to 
   // provide information about the design-time container.
   public override bool CanConvertFrom(ITypeDescriptorContext context, 
      Type sourceType) {
      
      if (sourceType == typeof(string)) {
         return true;
      }
      return base.CanConvertFrom(context, sourceType);
   }
   // Overrides the ConvertFrom method of TypeConverter.
   public override object ConvertFrom(ITypeDescriptorContext context, 
      CultureInfo culture, object value) {
      if (value is string) {
         string[] v = ((string)value).Split(new char[] {','});
         return new Point(int.Parse(v[0]), int.Parse(v[1]));
      }
      return base.ConvertFrom(context, culture, value);
   }
   // Overrides the ConvertTo method of TypeConverter.
   public override object ConvertTo(ITypeDescriptorContext context, 
      CultureInfo culture, object value, Type destinationType) {  
      if (destinationType == typeof(string)) {
         return ((Point)value).X + "," + ((Point)value).Y;
      }
      return base.ConvertTo(context, culture, value, destinationType);
   }
}

然后再传给你需要此方法的类

[TypeConverter(typeof(PointConverter ))]
 public class MyClass {
    // Insert code here.
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容