【问题标题】:Let a ComboBox to show a modified text as the value input instead of the actual value让 ComboBox 将修改后的文本显示为值输入而不是实际值
【发布时间】:2013-04-24 01:03:31
【问题描述】:

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

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

【问题讨论】:

  • 房产类型是什么?可以是自定义类吗?

标签: c# properties combobox propertygrid uitypeeditor


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-14
    • 1970-01-01
    • 1970-01-01
    • 2017-08-21
    • 1970-01-01
    相关资源
    最近更新 更多