I've developed a custom UserControl. When I add it to a form in design view, there is no obvious border around it (unless I change the BorderStyle
property to something other than None).
Some controls (such as PictureBoxes) have a dashed outline to 开发者_开发问答indicate the area they are using. Is there a way to do this for a UserControl?
I'm using C#, .NET 3.5, Windows Forms.
You'll need to write a custom designer for your UserControl, which is the same thing that WinForms does for the Panel control. The code in the designer class overrides the OnPaintAdornments
method in order to draw the dashed border around the control's client area.
The easiest way to get started is by inheriting from the ScrollableControlDesigner
class, which will give you most of the necessary functionality for free. Then add the logic into these methods:
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 };
}
}
}
Once you've done that, you'll need to instruct your UserControl class to use the custom designer you've written. That's done by adding the DesignerAttribute
to its class definition:
[Designer(typeof(MyUserControlDesigner)), DesignerCategory("UserControl")]
public class MyUserControl : UserControl
{
// insert your code here
}
And of course, this will require that you add a reference to System.Design.dll
to your assembly, forcing you to target the full version of the .NET Framework (rather than the "Client Profile").
精彩评论