2011-01-12 9 views

cevap

9

Bunu özelleştirmek zorundasınız.

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

Örnek kullanım: Bunun gibi

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

diğer dillerde bu işi yapmak için System.Globalization hiçbir yardım alın.

+0

Teşekkürler, kapatın, ancak değeri çift tıklattığımda bir Hata Dlg alıyorum "Özellik değeri geçerli değil"/"Türün nesnesi" System.String ',' System.Boolean 'türüne dönüştürülemiyor. " –

+0

Ugh, pita. Çalışma zamanında bunu hata ayıklamak için bir formda PropertyGrid koyun. –

+1

Boole için döküm yerine Sistem :: Dönüştürme :: ToBoolean (değer) gerekebilir. – ThePragmatist

3

Bir enum kullanarak özel dönüştürücü uygulama önlemek olabilir:

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

Olduğu gibi bu çözüm Yerelleştirilebilir değildir ve sen/Kapalı Açık" her permütasyon için bir enum uygulamak zorunda kalacak "kullanmak istediğiniz değer çiftleri. Ancak, bir kerelik için basit bir cevaptır.

İlgili konular