2013-07-18 57 views
0

使用時,每下面的示例代碼貼我能夠看到在下拉列表中值作爲風險和默認不按預期工作。默認值與自定義類型轉換器

但因爲我有一個設置[默認值(「風險」)名爲「DummyProperty」屬性上面我希望在屬性網格下拉選擇的風險值。但沒有發生。我在這裏錯過了什麼?

public partial class UserControl1 : UserControl 
{ 
    public UserControl1() 
    { 
     InitializeComponent(); 
    } 

    string sDummy; 

    [DefaultValue("Risk")] 
    [Category("Test")] 
    [ParamDesc("SystemType")] 
    [TypeConverter(typeof(PropertyGridTypeConverter))] 
    public String DummyProperty 
    { 
     get { return sDummy; } 
     set { sDummy = value; } 
    } 
} 

[AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)] 
public class ParamDesc : Attribute 
{ 
    public ParamDesc(string PD) 
    { PropDesc = PD; } 

    public string PropDesc 
    { get; set; } 

} 


class PropertyGridTypeConverter : TypeConverter 
{ 
    List<string> lst = new List<string>(); 

    public override bool GetStandardValuesSupported(ITypeDescriptorContext context) 
    { 
     return true; 
    } 

    public override StandardValuesCollection GetStandardValues(ITypeDescriptorContext context) 
    { 
     if (context != null) 
     { 
      AttributeCollection ua = context.PropertyDescriptor.Attributes; 
      ParamDesc cca = (ParamDesc)ua[typeof(ParamDesc)]; 

      switch (cca.PropDesc) 
      { 
       case "SystemType": 
        lst = new List<string> {"Risk", "Default"}; 
        break; 
       case "DateType": 
        lst = new List<string> {"Daily", "Monthly"}; 
        break; 
      } 
     } 
     lst.Sort(); 
     return new StandardValuesCollection(lst); 
    } 
} 
+0

您shuld在構造函數初始化'sDummy'。請參閱http://stackoverflow.com/a/1980533/2122718 – marbel82

回答

0

有點令人困惑的是,DefaultValue自定義屬性並未用於像所需的屬性上設置默認值。實際上,運行時並不直接使用它。它旨在用於Visual Studio設計人員。

你可能只是想在其他地方初始化值(如在構造函數中的UserControl1)。

點擊此處瞭解詳情: .Net DefaultValueAttribute on Properties