境界線があるカスタムパネルを作成しようとしました。その色は特定の条件下でパネルを「強調表示」するために変更できます。Dockに塗りつぶしを設定せずにパネル内のラベルを中央に配置する方法
パネルはまた、テキストを介して特定の情報を伝達する必要があります。この目的のために、ラベルをパネルに追加しました。私はラベルをセンタリングするために規定された方法を試しましたが、何らかの理由でそれは常にPanelの左上に配置します。 LabelのDockをFillに設定することはできません。これは、作成されたカスタム境界をカバーするためです。だから、レーベルが境界内に収まるようにする必要があります。
ラベルのアンカーがNoneに設定され、その場所が
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);
EDIT:プログラム的にパネルの中央にラベルを配置するの試み(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);
.NETのフォーム内の[センタリングコントロール(Winformsのが重複する可能性)?](http://stackoverflow.com/questions/491399/centering-controls-within-a-form-in-net-winforms) – Breeze
ラベルを中央に置き、アンカーを左、右に設定し、自動サイズをfalseに設定します –
I私の問題はLocatioと思うn。 AnchorプロパティとAutoSizeプロパティを設定しても何も行われません。私が正しいパネルの中央の計算ですか? – NickV987