2009-06-08 77 views
3

我想讓自己的用戶控件,幾乎完成它,只是試圖添加一些波蘭語。我想在設計器中選擇「在父容器中停靠」。有誰知道如何做到這一點,我找不到一個例子。我認爲這與Docking Attribute有關。用戶控件停靠屬性

+1

哪些錯誤與控制停靠屬性? – tanascius 2009-06-08 11:28:40

回答

5

我爲了實現這個目標,需要實現幾個類;首先,您需要定製ControlDesigner,然後您需要定製DesignerActionList。兩者都相當簡單。

的ControlDesigner:

public class MyUserControlDesigner : ControlDesigner 
{ 

    private DesignerActionListCollection _actionLists; 
    public override System.ComponentModel.Design.DesignerActionListCollection ActionLists 
    { 
     get 
     { 
      if (_actionLists == null) 
      { 
       _actionLists = new DesignerActionListCollection(); 
       _actionLists.Add(new MyUserControlActionList(this)); 
      } 
      return _actionLists; 
     } 
    } 
} 

的DesignerActionList:

public class MyUserControlActionList : DesignerActionList 
{ 
    public MyUserControlActionList(MyUserControlDesigner designer) : base(designer.Component) { } 

    public override DesignerActionItemCollection GetSortedActionItems() 
    { 
     DesignerActionItemCollection items = new DesignerActionItemCollection(); 
     items.Add(new DesignerActionPropertyItem("DockInParent", "Dock in parent")); 
     return items; 
    } 

    public bool DockInParent 
    { 
     get 
     { 
      return ((MyUserControl)base.Component).Dock == DockStyle.Fill; 
     } 
     set 
     { 
      TypeDescriptor.GetProperties(base.Component)["Dock"].SetValue(base.Component, value ? DockStyle.Fill : DockStyle.None); 
     } 
    }  
} 

最後,你需要將設計連接到您的控制:

[Designer("NamespaceName.MyUserControlDesigner, AssemblyContainingTheDesigner")] 
public partial class MyUserControl : UserControl 
{ 
    // all the code for your control 

簡要說明

該控件具有與其關聯的Designer屬性,該屬性指出了我們的自定義設計器。該設計師唯一的定製是DesignerActionList這是暴露。它創建我們自定義操作列表的一個實例,並將其添加到公開的操作列表集合中。

自定義操作列表包含bool屬性(DockInParent),併爲該屬性創建操作項。本身將返回true正在編輯的組件的Dock屬性的屬性是DockStyle.Fill,否則false,如果DockInParent設置爲true,組件的Dock屬性設置爲DockStyle.Fill,否則DockStyle.None

這將在設計器中顯示靠近控件右上角的小「動作箭頭」,單擊箭頭將彈出任務菜單。

3

如果您的控件繼承自UserControl(或大多數其他控件可用),則只需將Dock屬性設置爲DockStyle.Fill即可。

14

我也建議看看DockingAttribute

[Docking(DockingBehavior.Ask)] 
public class MyControl : UserControl 
{ 
    public MyControl() { } 
} 

這也會在控件的右上角顯示'action arrow'。

這個選項早在.NET 2.0中就可以使用,而且如果你正在尋找的是'父容器中的Dock/Undock'函數,它就簡單得多。在這種情況下,設計師類是巨大的矯枉過正。

它還給出DockingBehavior.NeverDockingBehavior.AutoDock的選項。 Never不顯示箭頭,並加載新控件的默認Dock行爲,而AutoDock顯示箭頭但自動將控件停靠在Fill。附:

PS:對不起,關於necromancing線程。我一直在尋找類似的解決方案,這是突然出現在谷歌的第一件事。該 設計師的屬性給了我一個想法,所以我就開始四處和 發現DockingAttribute,這似乎遠遠超過了公認的 解決方案與同一請求的結果更乾淨。希望這將有助於 人的未來。