2011-07-23 13 views
2

私はカスタムのUserControlを開発しました。デザインビューでフォームに追加すると、周囲に明白な境界線がありません(BorderStyleプロパティをNone以外に変更しない限り)。UserControlが枠線スタイルを持たないときにデザインビューで使用する領域を強調表示するにはどうすればよいですか?

一部のコントロール(ピクチャボックスなど)には、使用している領域を示す破線の輪郭があります。 UserControlのためにこれを行う方法はありますか?

私はC#、.NET 3.5、Windowsフォームを使用しています。

答えて

3

UserControl用のカスタムデザイナーを作成する必要があります。これは、WinFormsがPanelコントロール用に行うのと同じことです。デザイナクラスのコードは、コントロールのクライアント領域の周りに破線の枠線を描画するためにOnPaintAdornments methodをオーバーライドします。

最も簡単な方法は、無料で必要な機能のほとんどを提供するScrollableControlDesignerクラスを継承することです。そして、これらのメソッドにロジックを追加します。あなたはそれをやった

public class MyUserControlDesigner : ScrollableControlDesigner 
{ 
    public MyUserControlDesigner() 
    { 
     base.AutoResizeHandles = true; 
    } 

    protected override void OnPaintAdornments(PaintEventArgs p) 
    { 
     // Get the user control that we're designing. 
     UserControl component = (UserControl)base.Component; 

     // As you mentioned, no reason to draw this border unless the 
     // BorderStyle property is set to "None" 
     if (component.BorderStyle == BorderStyle.None) 
     { 
     this.DrawBorder(p.Graphics); 
     } 

     // Call the base class. 
     base.OnPaintAdornments(p); 
    } 

    protected virtual void DrawBorder(Graphics g) 
    { 
     // Get the user control that we're designing. 
     UserControl component = (UserControl)base.Component; 

     // Ensure that the user control we're designing exists and is visible. 
     if ((component != null) && component.Visible) 
     { 
     // Draw the dashed border around the perimeter of its client area. 
     using (Pen borderPen = this.BorderPen) 
     { 
      Rectangle clientRect = this.Control.ClientRectangle; 
      clientRect.Width--; 
      clientRect.Height--; 
      g.DrawRectangle(borderPen, clientRect); 
     } 
     } 
    } 

    protected Pen BorderPen 
    { 
     get 
     { 
     // Create a Pen object with a color that can be seen on top of 
     // the control's background. 
     return new Pen((this.Control.BackColor.GetBrightness() < 0.5) ?  
         ControlPaint.Light(this.Control.BackColor) 
         : ControlPaint.Dark(this.Control.BackColor)) 
         { DashStyle = DashStyle.Dash }; 
     } 
    } 
} 

たら、あなたが書いたカスタムデザイナーを使用するようにユーザーコントロールクラスを指示する必要があります。それは、そのクラス定義にDesignerAttributeを追加することによって行われます:

[Designer(typeof(MyUserControlDesigner)), DesignerCategory("UserControl")] 
public class MyUserControl : UserControl 
{ 
    // insert your code here 
} 

をそしてもちろん、これは、.NET Frameworkのフルバージョンをターゲットにあなたを強制的に、あなたはあなたのアセンブリにSystem.Design.dllへの参照を追加することを必要とします(「クライアントプロファイル」ではなく)。

+0

完全な.Netフレームワークは、typeofでない文字列refでDesignクラスを割り当てる場合は必要ありません。 http://archive.msdn.microsoft.com/WinFormsCustomCtrl – Wowa

+0

はい、ただし、開発マシンではまだ必要です。私は前にその記事で説明したことを正確に行ってきましたが、それは後部の巨大な痛みです。そしてそれほど価値はない:クライアントプロファイルは完全なフレームワークよりもずっと小さくない。 –

+0

開発マシンは常に完全な.netフレームワークを持つ必要があります。そして、Designクラスは開発者のためだけです:)しかし、誰かのためにアプリケーションを書く場合、クライアントのプロファイルだけを持っていれば完全な.netフレームワークをインストールする必要があります。 – Wowa

関連する問題