2009-02-06 37 views
3

我有一个从UserControl下降的用户控件。VisualStudio:如何在设计时将虚线边框添加到UserControl?

当放到表单上时,用户控件是不可见的,因为它没有任何类型的边框来显示它自己。

在设计时,PictureBox和Panel控件绘制一个虚线的1px边框以使其可见。

这样做的正确方法是什么?是否有一个属性可以用来使VS添加?

回答

3

没有财产会自动做到这一点。但是,您可以通过覆盖控件中的OnPaint并手动绘制矩形来对其进行归档。

在重写的事件中,您可以调用base.OnPaint(e)绘制控件内容,然后添加使用图形对象在边线周围绘制虚线。

protected override void OnPaint(PaintEventArgs e) 
    { 
     base.OnPaint(e); 

     if (this.DesignMode) 
      ControlPaint.DrawBorder(e.Graphics,this.ClientRectangle,Color.Gray,ButtonBorderStyle.Dashed); 
    } 

正如你看到的,你需要在查询控件DesignMode属性,因此只有在您的IDE绘制if语句来包装这个额外的代码。

0

Panel这样做的方式(这表明这是这样做的实际正确方法)是DesignerAttribute。此属性可用于设计时间添加到Control组件以及非控制组件(如Timer)。

使用DesignerAttribute时,您需要指定从IDesigner派生的类。对于具体的Control设计师,您应该从ControlDesigner中派生出来。

在您的ControlDesigner的特定实施中,您希望覆盖OnPaintAdornment。这种方法的目的是专门在控件之上绘制设计器提示,例如边框。

以下是Panel使用的实现。您可以复制该文件并将其用于您的控制,但您显然需要调整专门指向Panel课程的部分。

internal class PanelDesigner : ScrollableControlDesigner 
{ 
    protected Pen BorderPen 
    { 
     get 
     { 
      Color color = ((double)this.Control.BackColor.GetBrightness() < 0.5) ? ControlPaint.Light(this.Control.BackColor) : ControlPaint.Dark(this.Control.BackColor); 
      return new Pen(color) 
      { 
       DashStyle = DashStyle.Dash 
      }; 
     } 
    } 
    public PanelDesigner() 
    { 
     base.AutoResizeHandles = true; 
    } 
    protected virtual void DrawBorder(Graphics graphics) 
    { 
     Panel panel = (Panel)base.Component; 
     if (panel == null || !panel.Visible) 
     { 
      return; 
     } 
     Pen borderPen = this.BorderPen; 
     Rectangle clientRectangle = this.Control.ClientRectangle; 
     int num = clientRectangle.Width; 
     clientRectangle.Width = num - 1; 
     num = clientRectangle.Height; 
     clientRectangle.Height = num - 1; 
     graphics.DrawRectangle(borderPen, clientRectangle); 
     borderPen.Dispose(); 
    } 
    protected override void OnPaintAdornments(PaintEventArgs pe) 
    { 
     Panel panel = (Panel)base.Component; 
     if (panel.BorderStyle == BorderStyle.None) 
     { 
      this.DrawBorder(pe.Graphics); 
     } 
     base.OnPaintAdornments(pe); 
    } 
} 

ScrollableControlDesigner是,你可能会或可能不希望为您的特定设计的实施基地,使用一个公共类。