1

ユーザーがアイテムを選択するたびに、値の入力に異なるテキストを表示するプロパティを作成しようとしています。しかし、値に関する私の問題は、それらがアンダースコアと小文字の最初の文字を含む文字列であることです。たとえば、"naval_tech_school"です。そのため、代わりにこの「海軍技術学校」ComboBoxのような別の値のテキストを表示する必要があります。

ただし、アクセスしようとする場合、値は「naval_tech_school」のままにする必要があります。

4

1 に答える 1

0

2 つの形式の間で (特別なエディターを使用せずに) 値を変更するだけの場合は、カスタム 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
    }
}
于 2013-04-25T08:06:43.443 に答える