2011-03-06 105 views
0

我需要啓用任意對象的編輯屬性(只在運行時才知道對象的類型)。我創建了以下類:顯示PropertyGrid上動態類型對象的屬性

public class Camera 
{ 
    [TypeConverter(typeof(ExpandableObjectConverter))] 
    public object Configuration 
    { 
     get 
     { 
      return configuration; 
     } 
     set 
     { 
      configuration = value; 
     } 
    } 

    public Class1 a; 
    [TypeConverter(typeof(ExpandableObjectConverter))] 
    public Class1 A 
    { 
     get 
     { 
      return a; 
     } 
     set 
     { 
      a = value; 
     } 
    } 
} 

選擇對象「攝像機」,我能看到的Class1對PropertyGrid中的屬性後,但我看不到對象的屬性「配置」。我該如何解決這個問題?

+1

你已經發布了兩個問題,並沒有upvoted,或承認一個答案。承認人們的工作,你很可能會得到更多的幫助。 – 2011-03-06 18:40:00

回答

1

我的假設是,您的窗體在分配Configuration屬性之前變得可見。您沒有提供足夠的代碼來查看是否屬實。爲了測試我的關心,我創建了兩個配置對象:

public class Configuration1 
{ 
    public string Test { get; set; } 
    public byte Test1 { get; set; } 
    public int Test2 { get; set; } 
} 

public class Configuration2 
{ 
    public char Test3 { get; set; } 
    public List<string> Test4 { get; set; } 
} 

我修改你的相機類是這樣的:

public class Camera 
{ 
    public Camera() 
    { 
     Configuration1 = new Configuration1(); 
     Configuration2 = new Configuration2(); 
    } 
    private object configuration; 

    [TypeConverter(typeof(ExpandableObjectConverter))] 
    public object Configuration { get; set; } 

    [TypeConverter(typeof(ExpandableObjectConverter))] 
    public Configuration1 Configuration1 { get; set; } 

    [TypeConverter(typeof(ExpandableObjectConverter))] 
    public Configuration2 Configuration2 { get; set; } 
} 

然後我創建了一個形式與一個PropertyGrid和兩個Button實例。我配置形式的相互作用是這樣的:

public partial class Form1 : Form 
{ 
    private readonly Camera camera = new Camera(); 
    public Form1() 
    { 
     InitializeComponent(); 

     propertyGrid1.SelectedObject = camera; 
    } 

    private void Button1Click(object sender, System.EventArgs e) 
    { 
     camera.Configuration = new Configuration2(); 
     UpdatePropertyGrid(); 
    } 

    private void Button2Click(object sender, System.EventArgs e) 
    { 
     camera.Configuration = new Configuration1(); 
     UpdatePropertyGrid(); 
    } 

    private void UpdatePropertyGrid() 
    { 
     propertyGrid1.Refresh(); 
     propertyGrid1.ExpandAllGridItems(); 
    } 
} 

啓動視圖看起來像這樣:

enter image description here

點擊第二後:

enter image description here

點擊第一個按鈕後按鈕:

enter image description here

如果刪除刷新,屬性網格無法正常工作。另一種方法是在你的類和屬性上提供一個INotifyPropertyChanged接口。

+0

非常感謝。我解決了這個問題! 「刷新功能」是一個關鍵點! – user610801 2011-03-09 06:46:29