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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With