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

2

11

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 BooleanConverter may be all I need, but the standared BooleanConverter does not seem to let you set custom strings.

Guinna answered 12/1, 2011 at 13:43 Comment(0)
O
15

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.

Otherdirected answered 12/1, 2011 at 14:7 Comment(4)
Thanks, close, but when I double click on the value I get an Error Dlg "Property value is not valid" / "Object of type 'System.String' cannot be converted to type 'System.Boolean'."Guinna
Ugh, pita. Put a PropertyGrid on a form to debug this at runtime.Otherdirected
You might need System::Convert::ToBoolean(value) instead of the cast to bool.Blowy
@Ian: Your GetStandardValues method should not return your array of strings but an array of bools. And since the base BooleanConverter already does it, you can completely remove this method.Bieber
H
3

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.

Helotism answered 12/1, 2011 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.