我试图创建一个带有边框的自定义面板,其颜色可以更改,以便在某些条件下"突出显示"面板.
小组还需要通过案文传达某些信息.为此,我在Panel中添加了一个Label.我已尝试使用规定的方法对Label进行居中,但出于某种原因,它始终将其放在Panel的左上角.我无法将Label的Dock设置为Fill,因为它掩盖了已创建的自定义边框.所以我需要做到这一点,以便Label适合边框.
Label的Anchor设置为None,其位置为
new Point((ClientSize.Width - Size.Width)/2, (ClientSize.Height - Size.Height)/2);
Run Code Online (Sandbox Code Playgroud)
自定义Panel的代码是:
public class CustomPanel : Panel
{
public CustomPanel(int borderThickness, Color borderColor) : base()
{
SetStyle(ControlStyles.AllPaintingInWmPaint |
ControlStyles.UserPaint |
ControlStyles.OptimizedDoubleBuffer |
ControlStyles.ResizeRedraw, true);
BackColor = SystemColors.ActiveCaption;
BorderStyle = BorderStyle.FixedSingle;
Size = new Size(45, 45);
Margin = new Padding(0);
BorderThickness = borderThickness;
BorderColor = borderColor;
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
if (BorderStyle == BorderStyle.FixedSingle)
{
int halfThickness = BorderThickness / 2;
using (Pen p = new Pen(BorderColor, BorderThickness)) …Run Code Online (Sandbox Code Playgroud)