You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取属性指定的TypeConverter实例(如DevicesTypeConverter)?

解决属性专属TypeConverter获取问题

我懂你的困扰——直接从属性类型(string)拿转换器,肯定只会得到默认的StringConverter,要获取属性专属的DevicesTypeConverter,核心是从属性本身的自定义特性入手,而不是从属性类型层面去拿。下面给你一步步的解决方案:

1. 先确认属性已正确标记专属转换器

首先要保证你的目标属性已经通过TypeConverterAttribute明确指定了专属转换器,比如:

public class YourDeviceClass
{
    // 关键:给Conexion属性标记专属的DevicesTypeConverter
    [TypeConverter(typeof(DevicesTypeConverter))]
    public string Conexion { get; set; }

    // 你提到的依赖属性
    public string DeviceType { get; set; }
}

2. 通过PropertyInfo获取属性专属转换器实例

要拿到这个属性的DevicesTypeConverter,你需要先获取该属性的PropertyInfo,再从中提取转换器特性并实例化:

// 获取Conexion属性的PropertyInfo对象
var conexionProp = typeof(YourDeviceClass).GetProperty(nameof(YourDeviceClass.Conexion));
if (conexionProp == null) return;

// 读取属性上的TypeConverterAttribute特性
var converterAttr = conexionProp.GetCustomAttribute<TypeConverterAttribute>();
if (converterAttr == null) return;

// 加载转换器类型并实例化
var converterType = Type.GetType(converterAttr.ConverterTypeName);
if (converterType != null && typeof(TypeConverter).IsAssignableFrom(converterType))
{
    var devicesConverter = (TypeConverter)Activator.CreateInstance(converterType);
    // 这里就是你要的DevicesTypeConverter实例了!
}

3. 结合属性网格的依赖场景优化

针对你提到的「Conexion可选值依赖另一个属性」的需求,在DevicesTypeConverter里,你可以通过ITypeDescriptorContext获取当前编辑的对象实例,从而拿到依赖属性的值动态生成可选列表。比如重写GetStandardValues方法:

public class DevicesTypeConverter : StringConverter
{
    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
    {
        // 获取当前正在属性网格中编辑的对象实例
        var deviceInstance = context.Instance as YourDeviceClass;
        if (deviceInstance == null) return base.GetStandardValues(context);

        // 根据依赖属性DeviceType生成对应的可选连接值
        List<string> conexionOptions = new List<string>();
        switch (deviceInstance.DeviceType)
        {
            case "Network":
                conexionOptions.AddRange(new[] { "TCP/IP", "UDP", "HTTP" });
                break;
            case "Serial":
                conexionOptions.AddRange(new[] { "COM1", "COM2", "COM3" });
                break;
        }
        return new StandardValuesCollection(conexionOptions);
    }

    public override bool GetStandardValuesSupported(ITypeDescriptorContext context)
    {
        return true; // 启用可选值列表功能
    }
}

这样在属性网格里,当你修改DeviceType属性后,Conexion的可选值列表会自动更新,同时你也能通过前面的方法正确获取到专属的DevicesTypeConverter实例。

内容的提问来源于stack exchange,提问作者jstuardo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:23:05