2013-04-24 85 views
1

我试图做一个属性,将用户选择的项目,每次显示其值输入一个不同的文本的实际值。但我的值与问题是它们是带下划线和小写第一个字母的字符串,例如:“naval_tech_school”。所以,我需要的ComboBox以显示不同的值,文本看起来像这样“海军技术学校”来代替。让一个ComboBox显示修改后的文本作为值输入,而不是

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

+0

什么是属性的类型?它可以是一个自定义类吗? – 2013-04-24 07:57:33

回答

0

如果你只是想改变值(无特殊编辑器),来回两种格式之间,你只需要一个定义TypeConverter。财产申报是这样的:

public class MyClass 
{ 
    ... 

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

    ... 
} 

这里是一个样本类型转换器:

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 
    } 
} 
相关问题