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

时间:2013-04-24 01:03:32

标签: c# properties combobox propertygrid uitypeeditor

我正在尝试创建一个属性,每次用户选择一个项目时,它的值输入中都会显示不同的文本。但我对值的问题在于它们是带有下划线和小写首字母的字符串,例如:“naval_tech_school”。因此,我需要ComboBox来显示不同的值文本,而不是“Naval Tech School”

但如果尝试访问该值,该值应保持“naval_tech_school”

1 个答案:

答案 0 :(得分:0)

如果您只想在两种格式之间来回更改值(没有特殊编辑器),您只需要一个自定义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
    }
}