开发者

How do I show a bool property as Yes|No in the property grid?

开发者 https://www.devze.com 2023-02-04 01:03 出处:网络
I know I can do this by writing custom type descriptors etc., however given how simple this requirement is; am I missing an easy way of doing it.

I know I can do this by writing custom type descriptors etc., however given how simple this requirement is; am I missing an easy way of doing it.

Being able to set the string for "true" and "false" in the BooleanConv开发者_StackOverflow社区erter may be all I need, but the standared BooleanConverter does not seem to let you set custom strings.


You'll have to customize it. Like this:

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" };
}

Sample usage:

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

You get no help from System.Globalization to make this work in other languages.


You could avoid implementing a custom converter by using an enum:

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; }
}

As is, this solution isn't localizable, and you'd have to implement an enum for every permutation of "On/Off" value pairs you wanted to use. But, it's the simple answer for a one-off.

0

精彩评论

暂无评论...
验证码 换一张
取 消