【发布时间】: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