让ComboBox显示修改后的文本作为输入值,而不是实际值

本文关键字:输入 修改 显示 ComboBox 文本 | 更新日期: 2023-09-27 18:10:48

我试图使一个属性,将显示一个不同的文本在其值输入每次用户选择一个项目。但是我对这些值的问题是它们是带有下划线和小写字母的字符串,例如:"naval_tech_school"。所以我需要ComboBox显示一个不同的值文本,看起来像这样"Naval Tech School"

但是如果试图访问它,该值应该保持"naval_tech_school"

让ComboBox显示修改后的文本作为输入值,而不是实际值

如果您只想在两种格式之间来回更改值(不需要特殊的编辑器),则只需要自定义TypeConverter。像这样声明属性:

public class MyClass
{
    ...
    [TypeConverter(typeof(MyStringConverter))]
    public string MyProp { get; set; }
    ...
}

这里是一个TypeConverter示例:

public class MyStringConverter : TypeConverter
{
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
    }
    public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
    {
        return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
    }
    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
    {
        string svalue = value as string;
        if (svalue != null)
            return RemoveSpaceAndLowerFirst(svalue);
        return base.ConvertFrom(context, culture, value);
    }
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        string svalue = value as string;
        if (svalue != null)
            return RemoveUnderscoreAndUpperFirst(svalue);
        return base.ConvertTo(context, culture, value, destinationType);
    }
    private static string RemoveSpaceAndLowerFirst(string s)
    {
        // do your format conversion here
    }
    private static string RemoveUnderscoreAndUpperFirst(string s)
    {
        // do your format conversion here
    }
}