1. 程式人生 > >C# WinForm 中Label自動換行 解決方法

C# WinForm 中Label自動換行 解決方法

在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.


相關推薦

C# WinForm Label自動 解決方法

在TableLayoutPannel中放著一些Label 如果把Label的AutoSize屬性設成True的話,文字超過label長度時就會自動增加,直到後面的字出窗體以外 設定成False時,一旦到達Label的長度,後面的字元也就顯示不出來了 經過我的多番實踐,最

TextView英文自動解決方法

TextView元件 遇到一個問題: 想將【TP-LINK_XXXXXXX】已ellipsize="end'的方式展示一部分,設定 android:layout_width="400px" android:ellipsize="end" android:maxLines=

input不支援自動解決辦法

textarea與input input不支援換行; textarea: 1.支援換行; 2.左邊字型要想跑向左上角需要加程式碼; <textarea name="" id="" cols="" rows="" style="vertical-align:top;out

cocos2dx控制元件-----ListView的使用(label自動

float totalHeight = 0;if (m_textInfoListView){m_textInfoListView->removeAllChildrenWithCleanup(true);}m_textInfoListView = nullptr;m_t

DrawText自動功能

使用DrawText函式輸出文字,如果需要讓輸出的內容在指定矩形內自動換行,則可以使用DT_WORDBREAK選項。但根據API說明,該選項只能截斷單詞,即只在單詞間的空格處分割。如果輸出內容是一長串沒有空格分隔的ASCII碼(如英文字元或數字),那麼該長串會被當做一個單詞來處理而不會自動換行(中文字元沒有

C#RichTextBox的內容

RichTextBox顯示多行文字就得把它的Multiline屬性設定為true。直接加一個換行符"\n":RichTextBox1.Text = "First Line\nSecond Line\nThird Line";顯示的結果(沒有換行)為"First LineSec

DIV層字型自動

  對於table   1. (IE瀏覽器)使用樣式table-layout:fixed; eg. <style> .tb{table-layout:fixed} </style> <table class="tbl" width="80"> <tr> <

WPF控制元件TextBlock文字自動

在很多的WPF專案中,往往為了追求介面的美觀,需要控制控制元件中文字的換行顯示,現對TextBlock控制元件換行的實現方式進行總結,希望大家多多拍磚!!! 1.使用轉義字元 在XAML檔案中,實現方式如下: <TextBlock x:Name="textBlock

css實現連續數字和英文的自動方法

overflow 邊界 沒有 flow bre ref wid over IE 1.(IE瀏覽器)連續的英文字符和阿拉伯數字,使用word-wrap : break-word ;或者word-break:break-all;實現強制斷行 #wrap{word-break:b

C# WinForm頁面切換導致閃爍的解決方法

問題描述 介面上放置大量的控制元件(尤其是自定義控制元件)會導致在窗體載入時,速度變得緩慢;當切換頁面時,也會時常產生閃爍的問題,非常影響使用者體驗。 解決方法 將此程式碼寫在要解決閃爍問題的

htmltitle標籤方法

 今天一個朋友問我關於titile換行的問題,於是總結了一下,給大家分享! 1.將 title 屬性分成幾行來寫 <a   href="#"  title="第一行                    第二行">title換行</a>  2

Ubuntu使用過程滑鼠自動停止的解決方法

1. 安裝laptop-mode-tools sudo apt install laptop-mode-tools 2. 編輯runtime-pm.conf sudo vim /etc/laptop-mode/conf.d/runtime-pm.conf 3. 修改以

radio控制元件item設定自動方法

<radio id="radio" value=""> <item text="sksdkdksdsdssdsdsdsdsdsdsdasdadasdasdasdadsas

WinFormLabel控制元件的顯示

        WinForm中,Label控制元件是最常用的了。可有時需要它的換行,只能在後臺用\r\n或Environment.NewLine。原來,換行還可以通過前臺介面屬性設定來實現。 換行主要用到AutoSize、MaximumSize和Size三個屬性。新增一個

C#下 ASP.NET 2.0禁止GridView的內容自動 (測試有效!!)

有人喜歡換行,我不喜歡換行,經MSDN論壇高人解答,測試後有效: 在原始檔模式下的頭部加入定義             .brk         {                 white-space:pre;         } 然後在繫結事件後 e.Row.C

C#: WinForm系列——DataGridView單元格文字自動

DataGridView是.NET開發中常用的控制元件,在開發中發現大文字資料顯示時無法在介面上完全顯示,以下是我的解決方法。 (1)首先要保證單元格的為Text型別 (2)在程式中加入以下的程式碼片段 String str1 = "mac:192.168.0.121"; String str

asp.netLabel內容自動

可以做如下操作: <asp:Label ID="lblContent" runat="server" style="word-break:break-all" /> 或 前臺: <pre><asp:Label ID="lblPerSum" r

Swing支持自動的WrapLayout

vertica ancestor das ons blog ride prop app ember http://www.cnblogs.com/TLightSky/p/3482454.html —————&md

在td的輸入英文為什麽不自動???

ges .cn 寬度 輸入 內容 解決方法 alt 技術分享 英文 在表格中如果輸入純漢字,表格中的內容會根據表格大小進行換行,若果一個老外不會寫漢字,寫了一堆英文,表格的寬度會拉的很長,超過規定寬度 解決方法是在table中加上style="table-layout:

div li寬度不固定 ie6和ie7不兼容不自動

pwm https 不兼容 ofo http ace light href lan 我的li因為內容字數不一樣,所以寬度不固定,給他float:left屬性後,ie6和ie7不兼容,不自動換行!我給ul或者li: ul{white-space: nowrap} 屬性還是