如何在属性网格中将bool属性显示为Yes | No?

时间:2011-01-12 13:43:58

标签: .net winforms propertygrid

我知道我可以通过编写自定义类型描述符等来做到这一点,但是这个要求是多么简单;我错过了一种简单的方法。

能够在BooleanConverter中设置“true”和“false”的字符串可能就是我所需要的,但是标准的BooleanConverter似乎不允许你设置自定义字符串。

2 个答案:

答案 0 :(得分:11)

你必须自定义它。像这样:

class YesNoConverter : BooleanConverter {
    public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) {
        if (value is bool && destinationType == typeof(string)) {
            return values[(bool)value ? 1 : 0];
        }
        return base.ConvertTo(context, culture, value, destinationType);
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) {
        string txt = value as string;
        if (values[0] == txt) return false;
        if (values[1] == txt) return true;
        return base.ConvertFrom(context, culture, value);
    }

    private string[] values = new string[] { "No", "Yes" };
}

样本用法:

class MyControl : Control {
    [TypeConverter(typeof(YesNoConverter))]
    public bool Prop { get; set; }
}

您无法从System.Globalization中获得帮助,无法使用其他语言。

答案 1 :(得分:3)

您可以使用枚举来避免实现自定义转换器:

public enum YesNo{No,Yes}

...

[Browsable(true)]
public YesNo IsValueSet {get;set)

[Browsable(false)] //also consider excluding it from designer serialization
public bool ValueSetAsBool 
{
   get { return Convert.ToBoolean((byte)IsValueSet); }
   set { IsValueSet = value ? YesNo.Yes : YesNo.No; }
}

原样,此解决方案不可本地化,您必须为要使用的“On / Off”值对的每个排列实现枚举。但是,这是一次性的简单答案。