2016-02-19 48 views
2

請首先閱讀整個問題以瞭解其中我可以重置屬性的默認值。如何在'CollectionEditor'對話框中爲屬性啓用默認值

當定義,可以在視覺上設計的自定義類,可以實現一個集合編輯器來修改它們是列表,數組,集合性能,使用以下的模式:

[Editor(typeof(CollectionEditor), typeof(UITypeEditor)), 
    DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 
public ElementCollection Elements 
{ 
    get; 
} 

編輯的Elements屬性此課程現在將啓動CollectionEditor對話框,其左側爲成員名單,右側爲PropertyGrid

問題是,似乎這個屬性網格禁用了上下文菜單。因此,儘管定義了[DefaultValue]屬性,但我無法右鍵單擊某個屬性以將其值重置爲默認值。

然而,DefaultValue屬性被識別,因爲該屬性沒有被序列化(並且在網格內的未開卷文本中正確顯示)。

我想知道如何從CollectionEditor對話框上的PropertyGrid使這個上下文菜單

enter image description here

或替代,任何方式(熱鍵,),可以被實現爲能夠重置這些收集項目屬性。

回答

2

您可以創建自己的集合編輯器繼承CollectionEditor類,然後覆蓋CreateCollectionForm方法,發現在集合編輯器窗體屬性網格,然後註冊一個ContextMenuStrip包含復位菜單項屬性網格,然後重新使用ResetSelectedProperty屬性:

public class MyCollectionEditor : CollectionEditor 
{ 
    public MyCollectionEditor() : base(typeof(Collection<MyElement>)) { } 
    protected override CollectionForm CreateCollectionForm() 
    { 
     var form = base.CreateCollectionForm(); 
     var grid = form.Controls.Find("propertyBrowser", true).First() as PropertyGrid; 
     var menu = new ContextMenuStrip(); 
     menu.Items.Add("Reset", null, (s, e) => { grid.ResetSelectedProperty(); }); 
     //Enable or disable Reset menu based on selected property 
     menu.Opening += (s, e) => 
     { 
      if (grid.SelectedGridItem != null && grid.SelectedObject != null && 
       grid.SelectedGridItem.PropertyDescriptor.CanResetValue(null)) 
       menu.Items[0].Enabled = true; 
      else 
       menu.Items[0].Enabled = false; 
     }; 
     grid.ContextMenuStrip = menu; 
     return form; 
    } 
} 

和裝飾您的收藏屬性是這樣的:

[Editor(typeof(MyCollectionEditor), typeof(UITypeEditor))] 
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] 
public Collection<MyElement> MyElements { get; private set; } 

按照這種方法,您可以簡單地添加分隔符,命令和說明菜單。

+1

輝煌的解決方案! – Lemonseed