C# WinForm 中Label自动换行 解决方法

From: http://hi.baidu.com/tewuapple/blog/item/74070a2451cbcc7c36a80f76.html

在TableLayoutPannel中放着一些Label

如果把Label的AutoSize属性设成True的话,文字超过label长度时就会自动增加,直到后面的字出窗体以外

设置成False时,一旦到达Label的长度,后面的字符也就显示不出来了

经过我的多番实践,最佳的解决方法是

把Label的Dock属性设置成Fill,并同时把Label的AutoSize属性设成False。

以上只是一种简便的解决方法,如果以上方法解决不了问题,就老老实实计算控件大小以适应文本吧。

-----------------------------------------------------------------

具体方法:

C# WinForm中的Label,Button等控件在布局上和Web Application中不一样。
在WebApplication中,你可以指定它们的Width属性,然后当在指定Width内显示不全时,就自动换行,自动增加其Height 属性。
在WinForm中系统不会替你做这些事情。系统要求你必须同时指定Width和Height属性,缺一不可。当一行显示完而高度不足以显示第二行时,控件上的字符就会被截断。后面的字符就不会被显示出来了。

要实现WinForm中类似于WebApp的文本自动换行功能,你就必须手动编程设置控件的高度Height。在把控件添加进Form之前,应先获得控件控件显示文本的字数sumChar=Control.Text.Length,根据字数计算出需要多少行rowCount=(numChar/每行显示字数)+1 (注意:因为当不满一行时,(int)(numChar/每行显示字数)=0,因此必须再加一),那么控件的高度就是Control.Height=rowCount*每行文本的高度

在添加控件进Form之前,加入Control.Size = new Size (控件宽度,计算出来的控件高度)

OK。

应当注意的是,由于中英文以及各种符号的宽度不一致,所以每行显示的字数很难精确计算出来。可以根据显示内容以及经验,确定一个平均值,并且在完成之后多调试,最终确定一个合适的值。

-------------------------------------------------------------------------------

1.单行完全显示:Label.AutoSize = true;

2.换行显示:Label. AutoSize = false;(Label框高度用户指定)。

3.多行显示,并且根据字数自动控制高度:Label.AutoSize = true;Label.MaximumSize = new Size(w,0); 注:w:用户设定的宽度。

------------------------------------------------------

label自动换行的折衷方案:

核心关键在于利用TextBox的MultiLine自动换行功能,实现自动换行,其他就是颜色的设置、高度及所属窗体高度的自动调整。

采用TextBox来实现文字的自动换行,textBox背景色设置为:Control色,AutoSize = true;MultiLize = true;Height = 12;

每个字符占用的宽度大约是12;

然后添加以下代码:

           int LblNum = ConfStr.Length;                                             //TextBox内容长度
           int RowNum = (int) txtBoxSp.Width/12;                               //每行显示的字数(计算出来的)
           int RowHeight = 12;                                                             //每行的高度
           int ColNum = (LblNum - (LblNum / RowNum) * RowNum) == 0 ? (LblNum / RowNum) : (LblNum / RowNum) + 1;   //列数
            
           if(ColNum == 1)
           {
               this.Height = 278;                                                   //禁止窗体显示textBox;
               this.AutoSize = false;
           }
           else
           {
               txtBoxSp.AutoSize = true;                                         //设置AutoSize
               txtBoxSp.Height = RowHeight * ColNum;                   //设置显示高度
               this.Height = 303 + txtBoxSp.Height + 6;                  //实现窗体高度的自动调整
           }

------------------------------------------------------

The fundamental problem in 1.1

When label is set to AutoSize = true, it measures as if all the text wants to be on one line.  In order to have multiple lines of text in 1.1, the AutoSize property cannot be used.

Guessing in 1.1

When you drop a label on a form in version 1.0/1.1 it is set to AutoSize = false.  The label can be resized to force the text onto the next line based upon the width of the control.  However, guessing the right height for the label can be problematic – if it is not created tall enough, the text will cut off at the bottom.  If it’s too tall there will be embarrassing gaps of whitespace in the dialog.  To solve this, folks typically used Graphics.MeasureString() with the width the label was currently set to, then used the resultant height to set the size of the label. 

There’s all kinds of problems with the latter approach – it doesn’t take into account several extra spacing/non-client borders of the control, it’s not good for performance (if you’re using Control.CreateGraphics() can force the label’s handle to be created before it normally would, etc). …and finally if you upgrade in 2.0 to UseCompatibleTextRendering = false, the calculations will be wrong.

APIs to avoid Guessing in 2.0

The Label control now has a GetPreferredSize() method which takes wrapping constraints.  This method will take out all the headaches of guessing by taking into account all the details you might not know about, e.g. non-client borders/padding and the technology used to draw text.

Having your cake and eating it too: Strategies for Automatic Word Wrap in 2.0

It was difficult to get this right in previous versions of Windows Forms, as there was no concept of constraining size.  Updating label to support multiline constraints was a delicate balancing act as we did not want to break folks using 1.1.  (A 1.1 app should *just work* running on 2.0).  If using the regular layout stuff (i.e. not flow and table layout panels) the label should continue to work as before.

The easiest way of supporting multiline text just using “dock and anchor” layout engine was to honor a new property called MaximumSize. This gives the Label a constraining width by suggesting that the maximum width you can be is “xxxx”.  When a label is AutoSize = true, it takes into account its MaximumSize when calculating its PreferredSize.

The pitfall to using MaximumSize is that the size of the label is now fixed: if you want the label to increase in width as the dialog increases, you need to write code to increase the MaximumSize.  While this is not difficult, it would be better if we could write less code.

One possibility for fixing the Label’s MaximumSize quandary is to place the label in a FlowLayoutPanel.  When a FlowLayoutPanel is anchored left|right, it has a constraining width, which it passes onto the label.  Setting the FlowLayoutPanel to AutoSize = true, the FlowLayoutPanel will grow in height as the label grows. (The label actually had a constraining width as well when anchored, but for compatibility reasons chose to ignore it.)  Because the label is in a new layout container, it is free to honor the wrapping constraints without the possibility of breaking anyone.  As the dialog is resized, the FlowLayoutPanel is resized, which in-turn passes a new constraint to the label.

Now that we have the label dynamically changing height with respect to the width of the dialog, we have another problem to solve.  If there is another control directly underneath the label, the label can obscure the control directly underneath it.  We need to find a way to push the other controls down when the label grows in height.

We could add the control below it to the FlowLayoutPanel we’ve just added, but if we want finer control of the sizing relationship, the situation calls for a TableLayoutPanel.  Controlling sizing behavior in TableLayoutPanel means controlling the ColumnStyles and RowStyles.  There are three kinds of ColumnStyles and RowStyles in the TableLayoutPanel: Percentage, Absolute and AutoSize. 

Briefly: When the TableLayoutPanel control arranges its columns, it assigns priorities to each ColumnStyle in the following order:

1. Columns with ColumnStyle set to Absolute are considered first, and their fixed widths are allocated.
2. Columns with ColumnStyle set to AutoSize are sized to their contents.
3. Remaining space is divided among columns with ColumnStyle set to Percent.

By placing a label within a column that has specific a sizing behavior, the label will wrap.  When the label wraps, controls in rows below it will be pushed down if the RowStyle is set to AutoSize.

Here’s a quick table of the behavior of labels within a TableLayoutPanel (TLP) and why they behave that way.

TLP AutoSize

TLP ColumnStyle

Will Label Wrap?

Why?

True and False

Absolute

Yes

Known constraints

Since the column is absolute, we have a known dimension to pass to the label as a wrapping distance.

True and False

AutoSize

No

Unknown constraints

Setting the column to AutoSize implies that we don’t understand currently what the size of the column should be.  Therefore all AutoSize = true controls are asked, “given infinite space, what size would you prefer to be?”

False

Percentage

Yes

Known constraints

Since the table is AutoSize = false, we understand that the % style column is a percentage of the remaining space in the table.  Therefore we have a known dimension to pass to the label as a wrapping distance.

True

Percentage

No

Unknown constraints

Since the table is AutoSize = true, we don’t understand what % should mean, as in an AutoSize = true table, there should be no free space.  In this case, the TLP reverse-engineers what the size of the column should be based on the infinite preferred size of the contents.  E.g. if a control is 50% and it says it wants to be 100px, the other 50% column should be 100px big. 

In summary:

Use label.MaximumSize if:
If you have no controls beneath your label AND your label width will remain fixed.

Use label in an anchored, autosized FlowLayoutPanel if:
If you have no controls beneath your label AND your label width will grow as a function of the dialog width.

Use label in a TableLayoutPanel if:
You have controls beneath your label that need to be moved as a function of label text length.  You will have to play with the right balance of ColumnStyles and whether or not it is necessary to actually AutoSize the TableLayoutPanel itself. 

As a last resort:
If you still cant figure it out, set label.AutoSize = false, and set the label.Size = label.GetPreferredSize( … ) with custom text wrapping constraints.

Updates:
Labels set to FlatStyle.System never word wrap when AutoSize is set to true.  Some folks use FlatStyle.System to scoot the text over to line up with the edge of the panel.  You can change your Label.Margin.Left = 0 so it will line up with other controls with a Margin.Left = 3. 

If you want Wrapping RadioButtons and CheckBoxes read here.

See the designer generated code for the samples!


本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/406510.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

厂家官网常用链接

<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />1、 IBM develperWorks 中国http://www.ibm.com/developerworks/cn/特点&#xff1a;归档清晰&#xff0c;文档专业质量高&#xff0c;多名家作品&#xff1b;2、 DELL中文官…

axios (get post请求、头部参数添加)傻瓜式入门axios

傻瓜式入门&#xff0c;简单粗暴说用法 通过cdn引入js文件 <script src"https://unpkg.com/axios/dist/axios.min.js"></script>get请求&#xff0c;默认’Content-Type’: ‘application/json’&#xff0c;可在头部参数中&#xff0c;修改Content-Ty…

项目最终复审报告

“北航学堂”项目最终复审报告 一、团队成员简介 Sevens团队在M1和M2阶段都是一共有七名队员&#xff0c;M1阶段我们的团队成员有&#xff1a;陈少杰&#xff0c;金鑫&#xff0c;高孟烨&#xff0c;雷元勇&#xff0c;王迪&#xff0c;邓亚梅&#xff0c;郑培蕾&#xff1b;在…

按ESC关闭当前窗口

在WinForm中经常会需要实现这样的功能&#xff1a;按ESC关闭当前窗口&#xff0c;或者按不同的键&#xff0c;实现不同的功能。 下文以实现按ESC关闭当前窗口为例&#xff1a; protected override bool ProcessCmdKey(ref Message msg, Keys keyData){/*C:\Program Files\Micro…

旁门左道也谈cacti安装

cacti作为一个优秀的流量监控软件&#xff0c;很多人都在用它&#xff0c;很多人也很想使用它。但是后面的这很多人&#xff0c;确没有能用上它。为啥呢&#xff1f;有句话说&#xff1a;“今天很难过&#xff0c;明天很难熬&#xff0c;后天很美好&#xff0c;但是很多人在明天…

js二进制流转Blob对象。Blob对象再转File对象

JavaScript 二进制转文件 使用js将blob对象转file对象 前端处理后端返回的二进制流文件 js中Blob对象一般用法 js中关于Blob对象的介绍与使用 上传的文件对象 完整代码实例 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8…

Taro+react开发(61) 一条虚线

.companyIntroDetail_sep{width: 100%;height: 1px;background-color: #F3F3F3 }

javaScript学习之路(1)词法结构

1&#xff0c;javascript是区分大小写的语言 &#xff08;HTML不区分大小写&#xff0c;XHTML区分大小写&#xff09; 2.注释 行注释 // 段落注释 /*......*/3.直接量&#xff1a; 程序中直接使用的数据值 转载于:https://www.cnblogs.com/zxk3113/p/4226082.html

VC++中把一个对话框最小化到托盘[转载]

From: http://hi.baidu.com/maxlcl/blog/item/61e83c87de35e529c65cc3e0.html 一、托盘简介 所谓的“托盘”&#xff0c;在Windows系统界面中&#xff0c;指的就是下面任务条右侧&#xff0c;有系统时间等等的标志的那一部分。在程序最小化或挂起时&#xff0c;但有不希望占…

element-ui cascader 级联选择器 存最后一级id及回显

:props"{emitPath:false}" 加上这行就可以&#xff0c;只存最后一级id&#xff0c;且以最后一级id完整回显。<el-cascader expand-trigger"click" placeholder"请输入" filterable clearable:props"{emitPath:false}":options"…

freebsd点到点的ipsec ***

使用 FreeBSD 网关在两个被 Internet 分开的网络之间架设 ,以实现两个网络通过通道互访&#xff0c;IPsec 是一种建立在 Internet 协议 (IP) 层之上的协议&#xff0c;它能够让两个或更多主机以安全的方式来通讯&#xff0c;IPsec 既可以用来直接加密主机之间的网络通讯 (也就是…

怎么使用7zip进行分批压缩_怎么使用钢结构抛丸机对钢结构进行除锈?

我们生活中所见的钢结构用的时间长了以后都会产生锈渍&#xff0c;表面还会存在各种污浊物&#xff0c;所以说除锈处理是钢结构生产环节的一道主要工序&#xff0c;如果处理不好直接影响钢结构的品质和质量&#xff0c;使钢结构的维修周期缩短或影响使用寿命&#xff0c;有时会…

Taro+react开发(62) 开发者工具修改为网页调试

点击微信开发者工具---更改开发模式---网页模式

(简单) POJ 3984 迷宫问题,BFS。

Description 定义一个二维数组&#xff1a; int maze[5][5] {0, 1, 0, 0, 0,0, 1, 0, 1, 0,0, 0, 0, 0, 0,0, 1, 1, 1, 0,0, 0, 0, 1, 0, }; 它表示一个迷宫&#xff0c;其中的1表示墙壁&#xff0c;0表示可以走的路&#xff0c;只能横着走或竖着走&#xff0c;不能斜着走&…

一个托盘程序演示 -闹钟 Alert

From: http://www.vckbase.com/document/viewdoc/?id996 下载源代码 关键字&#xff1a;托盘 Tray   想必大家都看见过那些在系统托盘&#xff08;Tray&#xff09;中的程序吧&#xff0c;本文就演示了如何创建一个这样的托盘程序Alert。Alert是一个运行在系统托盘中的小…

watch的immediate使用

vue中watch不触发、不生效的解决办法及原理 Vue watch监听路由不生效&#xff0c;没反应 watch的immediate使用

[转]ODAC 应用技巧 (一)使用 ODAC 的 Net 方式

原文地址&#xff1a;ODAC 应用技巧 &#xff08;一&#xff09;使用 ODAC 的 Net 方式 使用 ODAC 的 Net 方式 nxyc_twz163.com 大多数应用程序使用 OCI 的ODAC 标准方式来连接 Oracle 数据库服务器。这是使用第三方开发语言设计 Oracle 应用程序最常用的方法。 所有的 OCI …

adam算法效果差原因_冷库制冷效果差原因

冷库常见的现象有冷库温度降不下来和下降缓慢的时候&#xff0c;现在对库温下降缓慢的原因简单分析&#xff1a;1、冷库工程由于隔热或密封性能差&#xff0c;导致冷量损耗大隔热性能差是由于管道、库房隔热墙等的保温层厚度不够&#xff0c;隔热和保温效果不良&#xff0c;它主…

解决hive交互模式退格键乱码

在hive的交互模式下&#xff0c;输入退格、方向键等&#xff0c;出现乱码&#xff0c;可以通过如下方法解决&#xff1a; 1、修改bashrc文件&#xff1a; vi ~/.bashrc 在文件最后添加一行&#xff1a; stty erase ^H。 2、使修改生效&#xff1a; source ~/.bashrc 这样&#…