我开发了一个自定义 UserControl。当我将它添加到设计 View 中的表单时,它周围没有明显的边框(除非我将 BorderStyle
属性更改为 None 以外的其他内容)。
一些控件(例如 PictureBoxes)有一个虚线轮廓来指示它们正在使用的区域。有没有办法为 UserControl 执行此操作?
我正在使用 C#、.NET 3.5、Windows 窗体。
最佳答案
您需要为您的 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 };
}
}
}
完成后,您需要指示您的 UserControl 类使用您编写的自定义设计器。这是通过添加 DesignerAttribute
来完成的到它的类定义:
[Designer(typeof(MyUserControlDesigner)), DesignerCategory("UserControl")]
public class MyUserControl : UserControl
{
// insert your code here
}
当然,这将要求您将对 System.Design.dll
的引用添加到您的程序集中,迫使您以 完整 版本的 .NET 为目标框架(而不是“客户资料”)。
关于c# - 当 UserControl 没有边框样式时,如何在设计 View 中突出显示 UserControl 使用的区域?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6799519/