在Windows窗体中,我有包含长文本的复选框列表,表单是可重新调整大小的..
我可以根据表单宽度在运行时自动包装文本吗?
您可以使用:
要制作Text
包装,你需要使AutoSize
属性为false并允许更大的Height
:
checkBox1.AutoSize = false;
checkBox1.Height = checkBox1.Height * 3; // or however many lines you may need
// style the control as you want..
checkBox1.CheckAlign = ContentAlignment.TopLeft;
checkBox1.TextAlign = ContentAlignment.TopLeft;
checkBox1.Anchor = AnchorStyles.Right;
checkBox1.Text = "12321312231232 13189892321 312989893123 ";
你需要考虑垂直布局..
也许FlowLayoutPanel
会帮助那里或者你想要使用Graphics.MeasureString
或TextRenderer.MeasureText(String, Font, Size)
来衡量所需的尺寸!
我尝试了很多方法,但最后这个方法经过了大量的研究后 -
我只是使用两个事件来检测包含控件的面板的尺寸变化然后我相应地调整了控件。
第一个事件是LayoutEventHandler,detecting resolution change的第二个事件
在这些事件中: -
1-考虑分辨率获得面板宽度(较低的接受分辨率为1024x768)
Rectangle resolution = Screen.PrimaryScreen.Bounds;
int panelWidth *= (int)Math.Floor((double)resolution.Width / 1024);
all controls上的2-循环并调整控制宽度以适合面板宽度(我减去10个像素的垂直滚动宽度),然后我从MeasureString函数得到控制高度,它取控制文本,字体和控制宽度,并返回控制尺寸。
(即我将高度乘以大致系数“1.25”以克服线高和填充)
foreach (var control in controls)
{
if (control is RadioButton || control is CheckBox)
{
control.Width = panelWidth - 10;
Font fontUsed = control.Font;
using (Graphics g = control.CreateGraphics())
{
SizeF size = g.MeasureString(control.Text, fontUsed, control.Width);
control.Height = (int)Math.Ceiling(size.Height * 1.25);
}
}
}