[英]Will Radiobutton created dynamically have fixed text size in Windows Form c#?
I have tried to create a radiobutton dynamically and add it to groupbox/form, but the whole text associated with the radiobutton is not getting displayed.我试图动态创建一个单选按钮并将其添加到分组框/表单中,但是与单选按钮关联的整个文本没有显示出来。 When the radiobutton is added from the designer, the whole text is getting displayed.
从设计器添加单选按钮时,将显示整个文本。 For dynamically adding radio button am I missing anything or are there any ways to do it?
对于动态添加单选按钮,我是否遗漏了什么或有什么方法可以做到? Please find the sample code below:
请在下面找到示例代码:
public partial class Form1 : Form
{
private void SelectMicrophone_Load(object sender, EventArgs e)
{
System.Windows.Forms.RadioButton r1 = new System.Windows.Forms.RadioButton(); //created a radiobutton
r1.Name = "Microphone(RealTex";
r1.Text = "Microphone(RealTex";
r1.Location = new System.Drawing.Point(15, 15);
this.groupBox1.Controls.Add(r1);
When you set the text property in the designer, it adjust the radio button to the new size to cover the width of the text.当您在设计器中设置 text 属性时,它会将单选按钮调整为新大小以覆盖文本的宽度。 By default I think the width is 90 and with the text above it is resized to a width of 124. So when you create the object at runtime, it is probably just keeping the width to 90. You can however just set r1.Width = 124 before adding it to your controls collection.
默认情况下,我认为宽度是 90,上面的文本被调整为 124 的宽度。所以当你在运行时创建对象时,它可能只是保持宽度为 90。但是你可以只设置 r1.Width = 124,然后再将其添加到您的控件集合中。
Keep in mind that you may not know the length each time so you could either set the width to the maximum size that you need or use the TextRender's .MeasureText method to get the size of the text and then just add 20 to that to cover the graphic of the radio button circle that also appears and set the result of the X property to your width before adding the radiobutton to the collection.请记住,您可能不知道每次的长度,因此您可以将宽度设置为您需要的最大尺寸,或者使用 TextRender 的 .MeasureText 方法来获取文本的大小,然后将其添加 20 以覆盖在将单选按钮添加到集合之前,也会出现的单选按钮圆圈的图形并将 X 属性的结果设置为您的宽度。
RadioButton r1 = new RadioButton();
r1.Text = "This is short text";
//Measure the Text property and get the width and add 20 to accomodate the circle
r1.Width = (TextRenderer.MeasureText(r1.Text, r1.Font)).Width + 20;
r1.Location = new Point(15, 15);
this.Controls.Add(r1);
//Just another RB with even longer text.
r1 = new RadioButton();
r1.Text = "This is even longer text that we want to show";
r1.Width = (TextRenderer.MeasureText(r1.Text, r1.Font)).Width + 20;
r1.Location = new Point(15, 35);
this.Controls.Add(r1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.