【问题标题】:type converter to convert a class type to another class type类型转换器将一个类类型转换为另一个类类型
【发布时间】:2022-08-18 16:58:43
【问题描述】:
using System;
using System.ComponentModel;
using System.Globalization;
using System.Reflection;
using System.Xaml;

namespace Example
{
    public class MyConverter : TypeConverter
    {
        public override object ConvertFrom( ITypeDescriptorContext context , CultureInfo culture , object value )
        {
            Type type1 = ( (dynamic) value ).GetType();
            Type type2 = typeof( Foo<> ).MakeGenericType( type1 );
            object instance = Activator.CreateInstance( type2 );
            PropertyInfo prp = type2.GetProperty( nameof( Foo<byte>.Value ) );
            prp.SetValue( instance , Convert.ChangeType( value , type1 ) );
            return instance;
        }

    }

    public class Foo<T>
    {
        public T Value { get; set; }
    }

    public class Bar
    {
        public int SomeNumber { get; set; }
    }

    public class MyClass
    {
        [TypeConverter( typeof( MyConverter ) )]
        public Foo<Bar> MyProperty { get; set; }

        public void ConvertImplicit()
        {
            string xml = \"<MyClass xmlns=\\\"http://Example\\\"> <MyClass.MyProperty> <Bar SomeNumber=\\\"5\\\" /> </MyClass.MyProperty> </MyClass>\";
            MyClass myClass = XamlServices.Parse( xml ) as MyClass;
        }

        public void ConvertExplicit()
        {
            MyConverter myConverter = new MyConverter();
            Bar bar = new Bar() { SomeNumber = 5 };
            Foo<Bar> target = myConverter.ConvertFrom( null , null , bar ) as Foo<Bar>;
        }

    }
}

显示的 TypeConverter 在显式转换时按预期工作,在 ConvertExplicit 中演示。当转换是隐式完成时,就像在 ConvertImplicit 中那样,抛出一个异常,表示无法设置 MyProperty。

抛出异常是因为没有像 ConvertExplicit 中那样完成最终转换。

当使用 TypeConverter 进行隐式转换时,例如使用 XamlServices 时,无法进行最终转换。

如何修改我的 TypeConverter 以像 Convert Explicit 一样工作(转换后没有最终转换)?

顺便说一句:要运行 ConvertImplicit 您需要将其添加到 AssemblyInfo.cs [程序集:XmlnsDefinition(\"http://Example\", \"Example\")]

    标签: c# xaml typeconverter


    【解决方案1】:

    根据documentation,XAML 将仅使用类型转换器从字符串转换,而不是从其他类型转换(例如您的示例中的Bar):

    出于 XAML 目的,它只是可以处理字符串的代码路径 重要的输入。

    【讨论】:

      猜你喜欢
      • 2020-12-02
      • 2012-03-28
      • 1970-01-01
      • 2011-04-10
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-24
      • 1970-01-01
      相关资源
      最近更新 更多