我想让一个面板有一个粗边框。我能以某种方式设置它吗?
PS,我正在使用 C#。对比 2008。
最佳答案
吉姆,
我制作了一个用户控件并给出了一个 ParentControlDesigner。正如我在评论中指出的那样,这不是您所要求的完美解决方案。但这应该是一个很好的起点。哦,仅供引用,我也有可自定义的边框颜色。我受到另一个 SO 帖子的启发来追求这个......这比我预期的要棘手。 要在设置边框大小时正确重新排列内容,请调用 PerformLayout。在 OnResize 中对 DisplayRectangle 的覆盖和对 SetDisplayRectLocation 的调用导致子控件的正确重新定位。同样,子控件在最左上角时没有预期的“0,0”……除非边框宽度设置为 0……并且 OnPaint 提供边框的自定义绘图。
祝你好运!制作作为父级的自定义控件很棘手,但并非不可能。
[Designer(typeof(ParentControlDesigner))]
public partial class CustomPanel : UserControl
{
Color _borderColor = Color.Blue;
int _borderWidth = 5;
public int BorderWidth
{
get { return _borderWidth; }
set { _borderWidth = value;
Invalidate();
PerformLayout();
}
}
public CustomPanel() { InitializeComponent(); }
public override Rectangle DisplayRectangle
{
get
{
return new Rectangle(_borderWidth, _borderWidth, Bounds.Width - _borderWidth * 2, Bounds.Height - _borderWidth * 2);
}
}
public Color BorderColor
{
get { return _borderColor; }
set { _borderColor = value; Invalidate(); }
}
new public BorderStyle BorderStyle
{
get { return _borderWidth == 0 ? BorderStyle.None : BorderStyle.FixedSingle; }
set { }
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaintBackground(e);
if (this.BorderStyle == BorderStyle.FixedSingle)
{
using (Pen p = new Pen(_borderColor, _borderWidth))
{
Rectangle r = ClientRectangle;
// now for the funky stuff...
// to get the rectangle drawn correctly, we actually need to
// adjust the rectangle as .net centers the line, based on width,
// on the provided rectangle.
r.Inflate(-Convert.ToInt32(_borderWidth / 2.0 + .5), -Convert.ToInt32(_borderWidth / 2.0 + .5));
e.Graphics.DrawRectangle(p, r);
}
}
}
protected override void OnResize(EventArgs e)
{
base.OnResize(e);
SetDisplayRectLocation(_borderWidth, _borderWidth);
}
}
关于c# - 我想让面板有一个粗边框。我能以某种方式设置它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1852829/