添加为外部程序中的类型注册类型转换器的方法
This commit is contained in:
49
DeedyDesigner/Deedy.Testing/ExternalTypeConverter.cs
Normal file
49
DeedyDesigner/Deedy.Testing/ExternalTypeConverter.cs
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
using System;
|
||||||
|
using System.ComponentModel;
|
||||||
|
using System.ComponentModel.DataAnnotations;
|
||||||
|
using System.Diagnostics.CodeAnalysis;
|
||||||
|
using System.Globalization;
|
||||||
|
|
||||||
|
|
||||||
|
/*
|
||||||
|
public partial class App : Application
|
||||||
|
{
|
||||||
|
protected override void OnStartup(StartupEventArgs e)
|
||||||
|
{
|
||||||
|
base.OnStartup(e);
|
||||||
|
|
||||||
|
// 注册外部类型的「TypeConverter」
|
||||||
|
TypeDescriptor.AddAttributes(typeof(ExternalPerson),
|
||||||
|
new TypeConverterAttribute(typeof(ExternalPersonConverter)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
// 在目标程序集中定义类型时添加转换器
|
||||||
|
[TypeConverter(typeof(ExternalTypeConverter))]
|
||||||
|
public class ExternalType {
|
||||||
|
public ExternalType(string? value) { }
|
||||||
|
}
|
||||||
|
// 在主程序集中定义元数据类
|
||||||
|
[TypeConverter(typeof(ExternalTypeConverter))]
|
||||||
|
public class ExternalTypeMetadata { }
|
||||||
|
|
||||||
|
// 关联元数据与外部类型
|
||||||
|
[MetadataType(typeof(ExternalTypeMetadata))]
|
||||||
|
public partial class ExternalTypeProxy
|
||||||
|
{
|
||||||
|
// 通过代理类访问外部类型
|
||||||
|
[AllowNull]
|
||||||
|
public ExternalType Target { get; set; }
|
||||||
|
}
|
||||||
|
public class ExternalTypeConverter : TypeConverter
|
||||||
|
{
|
||||||
|
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) => sourceType == typeof(string);
|
||||||
|
|
||||||
|
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value)
|
||||||
|
{
|
||||||
|
return new ExternalType(value.ToString());
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user