【发布时间】:2016-12-25 17:16:56
【问题描述】:
我尝试创建一个带有边框的自定义面板,可以更改其颜色以在某些条件下“突出显示”面板。
小组还需要通过文本传达某些信息。为此,我在面板中添加了一个标签。我已经尝试了将标签居中的规定方法,但由于某种原因,它总是将它放在面板的左上角。我无法将标签的 Dock 设置为 Fill,因为这会覆盖已创建的自定义边框。所以我需要使标签适合边框。
标签的锚点设置为无,其位置为
new Point((ClientSize.Width - Size.Width)/2, (ClientSize.Height - Size.Height)/2);
自定义面板的代码是:
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))
{
e.Graphics.DrawRectangle(p, new Rectangle(halfThickness,
halfThickness,
ClientSize.Width - BorderThickness, ClientSize.Height - BorderThickness));
}
}
}
public int BorderThickness { get; set; }
public Color BorderColor { get; set; }
}
表格代码为:
private void NewPanelTest_Load(object sender, EventArgs e)
{
CustomPanel cp = new CustomPanel(3, Color.Black);
// Create new Label
Label info = new Label()
{
Size = new Size(30, 30),
Text = "Info",
Anchor = AnchorStyles.None,
TextAlign = ContentAlignment.MiddleCenter,
Enabled = false,
Font = new Font("Microsoft Sans Serif", 6),
ForeColor = Color.White,
Location = new Point(ClientSize.Width/2 - Width/2, ClientSize.Height/2 - Height/2)
};
cp.Controls.Add(info);
this.Controls.Add(cp);
}
编辑:我查看了类似的问题并尝试更改标签的属性,但没有结果。
// Create new Label
Label info = new Label()
{
// Same code as before
// Different code
Left = (this.ClientSize.Width - Size.Width) / 2,
Top = (this.ClientSize.Height - Size.Height) / 2,
//Location = new Point(ClientSize.Width/2 - Width/2, ClientSize.Height/2 - Height/2)
};
我也尝试过更改面板的填充,也没有结果。
Padding = new Padding(5);
编辑:尝试以编程方式将标签放置在面板的中心(产生 X = 0,Y = 0 的结果)
// Create new Label
Label info = new Label()
{
// Same code as before (excluding "Left", "Top", and "Location")
};
int X = (info.ClientSize.Width - info.Width) / 2;
int Y = (info.ClientSize.Height - info.Height) / 2;
info.Location = new Point(X, Y);
MessageBox.Show(info.Location.ToString());
cp.Controls.Add(info);
【问题讨论】:
-
将标签放在中间并将锚点左、右和自动调整为false
-
我认为我的问题在于位置。设置 Anchor 和 AutoSize 属性不会做任何事情。我对面板中间的计算是否正确?
-
@Breeze 我已经看过了,那里的计算与我所拥有的基本相同。我什至尝试使用 Top 和 Left 属性来实现它,但没有运气。我也尝试过调整 Padding 属性,但仍然没有。
-
在工具箱中的所有控件中,Label 和 PictureBox 是迄今为止最浪费的。只是点击方便,它们不值得您节省很长时间的单行代码。请改用 TextRenderer.DrawText()。你需要 ResizeRedraw = true 在构造函数中。
标签: c# winforms label border center