How can I make the text of checkbox wraps automatically with changing form width? [closed]

人走茶凉 提交于 2019-12-24 14:14:33

问题


In windows forms I have checkbox list that contains long text, the form is re-sizable..

can I make the text wraps automatically in run-time according to the form width ?


回答1:


You can by using:

  1. set 'autosize' to 'false'

  2. change the width of 'MaximumSize' to the label width you want, say '70'

  3. change the height of 'MinimumSize' to the label height you want, say '30'




回答2:


To make the Text wrap you need to make the AutoSize property false and allow for a larger 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 ";

You will need to think about the vertical layout..

Maybe a FlowLayoutPanel will help there or maybe you want to measure the size needed by using Graphics.MeasureString or TextRenderer.MeasureText(String, Font, Size)!




回答3:


I tried many approaches but at last this one worked after a lot of researches:-

simply I used two events to detect size change of the panel contains the controls then I adjusted the controls accordingly..

first event is LayoutEventHandler, second event for detecting resolution change

in these events:-

1- get the panel width considering the resolution (lower accepted resolution is 1024x768)

  Rectangle resolution = Screen.PrimaryScreen.Bounds;
  int panelWidth *= (int)Math.Floor((double)resolution.Width / 1024);

2- loop on all controls and adjust the control width to fit the panel width (i subtracted 10 pixels for vertical scroll width), then I got the control height from MeasureString function which takes the control text, the font and control width, and return the control size.

(i.e. I multiplied the height with a roughly factor "1.25" to overcome line height and padding)

  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);
            }
       }
  }


来源:https://stackoverflow.com/questions/26588506/how-can-i-make-the-text-of-checkbox-wraps-automatically-with-changing-form-width

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!