【发布时间】:2017-12-01 09:27:22
【问题描述】:
我想在列表框中创建一个换行符,这样文本就不会一直拖到用户无法阅读文本的全部内容的地方。
我希望当文本到达列表框的末尾时,它会下降到下一行,简单来说,就是自动换行。上网一搜,发现无法使用listbox实现自动换行功能。我设法在网上找到了一个自动换行算法并决定使用它,但是我不确定如何将它实现到我希望它所在的列表框中。
这是我找到的代码:
//https://www.codeproject.com/Articles/51488/Implementing-Word-Wrap-in-C
public static string WordWrap(string text, int width)
{
int pos, next;
StringBuilder sb = new StringBuilder();
// Lucidity check
if (width < 1)
return text;
// Parse each line of text
for (pos = 0; pos < text.Length; pos = next)
{
// Find end of line
int eol = text.IndexOf(Environment.NewLine, pos);
if (eol == -1)
next = eol = text.Length;
else
next = eol + Environment.NewLine.Length;
// Copy this line of text, breaking into smaller lines as needed
if (eol > pos)
{
do
{
int len = eol - pos;
if (len > width)
len = BreakLine(text, pos, width);
sb.Append(text, pos, len);
sb.Append(Environment.NewLine);
// Trim whitespace following break
pos += len;
while (pos < eol && Char.IsWhiteSpace(text[pos]))
pos++;
} while (eol > pos);
}
else sb.Append(Environment.NewLine); // Empty line
}
return sb.ToString();
}
/// <summary>
/// Locates position to break the given line so as to avoid
/// breaking words.
/// </summary>
/// <param name="text">String that contains line of text</param>
/// <param name="pos">Index where line of text starts</param>
/// <param name="max">Maximum line length</param>
/// <returns>The modified line length</returns>
private static int BreakLine(string text, int pos, int max)
{
// Find last whitespace in line
int i = max;
while (i >= 0 && !Char.IsWhiteSpace(text[pos + i]))
i--;
// If no whitespace found, break at maximum length
if (i < 0)
return max;
// Find start of whitespace
while (i >= 0 && Char.IsWhiteSpace(text[pos + i]))
i--;
// Return length of text before whitespace
return i + 1;
}
目前我把它作为一个单独的方法,我应该把这个方法直接放在列表框方法本身吗?
如果是,我该如何修改上述代码以使其工作? 顺便说一句 descLb 是我的列表框的名称
请不要建议我将我的列表框更改为另一种形式(例如文本框),我只知道如何从数据库中提取文本以输入到列表框并保持简单,我想使用列表框。
【问题讨论】:
-
我刚才已经提供了答案。请检查并告诉我。