简体   繁体   中英

c# custom Panel

I'm trying to create a custom panel containing some buttons and labels. The problem is that I can't set displaying order properly in code. I have something like this:

 public partial class Pallete1 : Panel
    {
        private Label lblAutomatic;       
        private Label lbldivider1;

        public Pallete1():base()
        {
            InitializeComponent();
            this.lblAutomatic = new Label();
            this.lbldivider1 = new Label();

            this.lblAutomatic.Size = new Size(182,21);
            this.lblAutomatic.Location = new Point(0, 0);
            this.lblAutomatic.ForeColor = Color.FromArgb(0, 0, 64);
            this.lblAutomatic.TextAlign = ContentAlignment.MiddleCenter;
            this.lblAutomatic.Text = "Automatycznie";
            this.lblAutomatic.Font = new Font("Microsoft Sans Serif", 8);

            this.lbldivider1.Size = new Size(2,22);
            this.lbldivider1.Location = new Point(26, 0);
            this.lbldivider1.ForeColor = SystemColors.ControlText;
            this.lbldivider1.BackColor = SystemColors.ButtonHighlight;
            this.lbldivider1.BorderStyle = BorderStyle.Fixed3D;


            this.Size = new Size(182, 184);
            this.BackColor = SystemColors.ButtonHighlight;
            this.BorderStyle = BorderStyle.FixedSingle;
            this.Controls.AddRange(new Control[]{this.lblAutomatic,this.lbldivider1});

        }

I would like lbldivider1 to be on the top of lblAutomatic . When I add this item to some WinForm projects, this second label is only seen when I drag my custom panel from one place to another. However it's not seen in the designer when it's not moving and also when I'm launching the application.

How can I fix it?

Ok, if you don't have some hidden code, any of the following should work:

(A)

this.Controls.AddRange(new Control[]{this.lblAutomatic,this.lbldivider1});
this.lbldivider1.BringToFront();

(B)

this.Controls.AddRange(new Control[]{this.lblAutomatic,this.lbldivider1});
this.lblAutomatic.SendToBack();

(C) Simply swap when adding (make sure lbldivider1 goes first in z order)

this.Controls.AddRange(new Control[]{this.lbldivider1, this.lblAutomatic});

如果要将标签的位置设置在第二个之上,请使用 ZOrder 属性,如果将一个放在另一个之下,您将选择 TableLayoutPanel 或 FlowLayoutPanel。

As per this question it seems ZOrder is a VB property not available in C#, however there is a SetChildIndex on the parent's Controls collection.

Try

this.Controls.SetChildIndex(lblAutomatic, 1);
this.Controls.SetChildIndex(lbldivider1, 2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM