为动态创建的控件设置锚点

时间:2017-03-16 07:27:58

标签: c# winforms radio-button

我有winform,动态创建了52个单选按钮。 这是创建它们的方法:

    private void CreateRadioButton()
    {            
        int rbCount = 52;
        int numberOfColumns = 23;

        radioButtons = new RadioButton[rbCount];
        int y = 520;

        for (int i = 0; i < rbCount; i++)
        {
            radioButtons[i] = new RadioButton();
            radioButtons[i].Text = Convert.ToString(i + 1);

            if (i % numberOfColumns == 0) 
                y += 20;

            var x = 11 + i % numberOfColumns * 50;

            radioButtons[i].Location = new Point(x, y);
            radioButtons[i].Size = new Size(40, 15);
            //radioButtons[i].Anchor = AnchorStyles.Left;
            //radioButtons[i].Anchor = AnchorStyles.Bottom;
            radioButtons[i].Font = new Font(radioButtons[i].Font.FontFamily, 8, FontStyle.Bold);
            radioButtons[i].UseVisualStyleBackColor = true;
            radioButtons[i].Click += new EventHandler(rbtns_click);

            xtraTab.Controls.Add(radioButtons[i]);            
        }          

    }

表格最大化时有问题。单选按钮消失。 如果我设置

 radioButtons[i].Anchor = AnchorStyles.Left;
 radioButtons[i].Anchor = AnchorStyles.Bottom;

单选按钮被重叠。

如果调整表单大小,我该怎样做才能保住他们在同一个地方的位置?

1 个答案:

答案 0 :(得分:2)

这两行

AnchorStyles.Left

表示Anchor值AnchorStyles.Bottom将替换为AnchorStyles

Flags设置了radioButtons[i].Anchor = AnchorStyles.Left | AnchorStyles.Bottom; 属性,可以合并枚举值:

this.radioButton1.Anchor = ((System.Windows.Forms.AnchorStyles)
   ((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));

如果通过Designer设置,则在&#34; Windows窗体设计器生成的代码&#34;它看起来像这样:

#books_div {
  position: absolute;
    left: 50%;
    top: 25%;
    transform: translatex(-50%);
}

#books_text {
  position: absolute;
    left: 50%;
    top: 15%;
    transform: translatex(-50%);
}


#name {
  background-color: #aaa;
  margin-bottom: 20px !important;
}