2009-10-29 81 views
0

我正在編寫一個應用程序,它允許用戶更改文本框或標籤的屬性,這些控件是用戶控件。爲每個用戶控件創建一個單獨的類,實現我希望它們能夠更改的屬性,然後將這些屬性綁定回用戶控件,最簡單嗎?還是有另一種我忽略的方法?C#屬性網格

回答

1

創建一個自定義屬性,並用這個屬性標記用戶想要編輯的屬性。然後在屬性網格的BrowsableAttribute屬性設置爲僅包含您的自定義屬性的集合:

public class MyForm : Form 
{ 
    private PropertyGrid _grid = new PropertyGrid(); 

    public MyForm() 
    { 
     this._grid.BrowsableAttributes = new AttributeCollection(new UserEditableAttribute()); 
     this._grid.SelectedObject = new MyControl(); 
    } 
} 

public class UserEditableAttribute : Attribute 
{ 

} 

public class MyControl : UserControl 
{ 
    private Label _label = new Label(); 
    private TextBox _textBox = new TextBox(); 

    [UserEditable] 
    public string Label 
    { 
     get 
     { 
      return this._label.Text; 
     } 
     set 
     { 
      this._label.Text = value; 
     } 
    } 

    [UserEditable] 
    public string Value 
    { 
     get 
     { 
      return this._textBox.Text; 
     } 
     set 
     { 
      this._textBox.Text = value; 
     } 
    } 
} 
+0

我明白了,我給這個一杆。非常感謝。 – Nathan 2009-10-29 15:20:54

+0

菲利普在這裏是一個不同的過程嗎? http://www.c-sharpcorner.com/UploadFile/mgold/PropertyGridInCSharp11302005004139AM/PropertyGridInCSharp.aspx 此外,如果您知道如何添加組合框到屬性網格? – Nathan 2009-10-29 21:31:45

+0

看看這篇文章: http://www.codeproject.com/KB/tabs/PropertyGridValidation.aspx – 2009-10-30 12:34:14