2011-09-16 25 views
0
  1. 有沒有辦法改變運行時的propertygrid griditem行爲?我需要的是我有一個屬性說「教育」,如果用戶選擇「大師」,那麼下一個網格項將在下拉控件中顯示與主控相關的教育。如果用戶在教育中選擇「其他」,則下一個控件將是文本框類型以便用戶輸入。我知道如何顯示下拉控件,只有我需要如何根據用戶選擇切換這兩個控件。如何在運行時更改propertygrid griditem行爲?

  2. 還有一個問題,有沒有辦法在運行時將griditem屬性「Browsable」設置爲false/true?

這可能嗎?

+0

這兩個問題的答案都與[本文] [1]中的相同。 [1]:http://stackoverflow.com/questions/7359649/c-propertygrid-how-to-change-visible-properties-at-runtime/7373746#7373746 – DeCaf

+0

我尋找示例代碼。 –

回答

1

由於您的示例代碼之後,像下面應該讓你開始:

//Represents each property to show in the control, required since 
//PropertyDescriptor is declared abstract 
public class MyPropertyDescriptor : PropertyDescriptor 
{ 
    public MyPropertyDescriptor(string name, Attribute[] attrs) : base(name, attrs) 
    { 
    } 
} 

//This is the class that is bound to the PropertyGrid. Using 
//CustomTypeDescriptor instead of ICustomTypeDescriptor saves you from 
//having to implement all the methods in the interface which are stubbed out 
//or default to the implementation in TypeDescriptor 
public class MyClass : CustomTypeDescriptor 
{ 
    //This is the property that controls what other properties will be 
    //shown in the PropertyGrid, by attaching the RefreshProperties 
    //attribute, this will tell the PropertyGrid to query the bound 
    //object for the list of properties to show by calling your implementation 
    //of GetProperties 
    [RefreshProperties(RefreshProperties.All)] 
    public int ControllingProperty { get; set; } 

    //Dependent properties that can be dynamically added/removed 
    public int SomeProp { get; set; } 
    public int SomeOtherProp { get; set; } 

    //Return the list of properties to show 
    public PropertyDescriptorCollection GetProperties(Attribute[] attributes) 
    { 
     List<MyPropertyDescriptor> props = new List<MyPropertyDescriptor>(); 

     //Insert logic here to determine what properties need adding to props 
     //based on the current property values 

     return PropertyDescriptorCollection(props.ToArray()); 
    } 
} 

現在,當您的MyClass一個實例綁定到PropertyGrid中,你的GetProperties執行將被調用,讓你有機會通過相應地填充屬性集合來確定要顯示的屬性。