【发布时间】:2012-01-25 02:32:11
【问题描述】:
WPF 中是否有相当于 .Lines 的 winForms?
我目前正在使用这个:
var textRange = new TextRange(TextInput.Document.ContentStart, TextInput.Document.ContentEnd);
string[] lines = textRange.Text.Split('\n');
【问题讨论】:
WPF 中是否有相当于 .Lines 的 winForms?
我目前正在使用这个:
var textRange = new TextRange(TextInput.Document.ContentStart, TextInput.Document.ContentEnd);
string[] lines = textRange.Text.Split('\n');
【问题讨论】:
RichTextBox 是 FlowDocument 类型,没有 Lines 属性。你正在做的似乎是一个很好的解决方案。您可能想使用IndexOf 而不是拆分。
您也可以像文章建议的那样添加扩展方法:
public static long Lines(this string s)
{
long count = 1;
int position = 0;
while ((position = s.IndexOf('\n', position)) != -1)
{
count++;
position++; // Skip this occurance!
}
return count;
}
【讨论】:
我知道我参加聚会很晚了,但我想出了另一个使用 RTF 解析的可靠且可重用的解决方案。
在 RTF 中,每个段落都以 \par 结尾。所以例如如果您输入此文本
Lorem ipsum
Foo
Bar
在RichTextBox 中,它将在内部存储为(非常非常简单)
\par
Lorem ipsum\par
Foo\par
Bar\par
因此,简单地统计那些\par 命令的出现次数是一种非常可靠的方法。请注意,\par 总是比实际行数多 1 个。
感谢extension methods,我提出的解决方案可以像这样简单地使用:
int lines = myRichTextBox.GetLineCount();
其中myRichTextBox 是RichTexBox 类的一个实例。
public static class RichTextBoxExtensions
{
/// <summary>
/// Gets the content of the <see cref="RichTextBox"/> as the actual RTF.
/// </summary>
public static string GetAsRTF(this RichTextBox richTextBox)
{
using (MemoryStream memoryStream = new MemoryStream())
{
TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
textRange.Save(memoryStream, DataFormats.Rtf);
memoryStream.Seek(0, SeekOrigin.Begin);
using (StreamReader streamReader = new StreamReader(memoryStream))
{
return streamReader.ReadToEnd();
}
}
}
/// <summary>
/// Gets the content of the <see cref="RichTextBox"/> as plain text only.
/// </summary>
public static string GetAsText(this RichTextBox richTextBox)
{
return new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
}
/// <summary>
/// Gets the number of lines in the <see cref="RichTextBox"/>.
/// </summary>
public static int GetLineCount(this RichTextBox richTextBox)
{
// Idea: Every paragraph in a RichTextBox ends with a \par.
// Special handling for empty RichTextBoxes, because while there is
// a \par, there is no line in the strict sense yet.
if (String.IsNullOrWhiteSpace(richTextBox.GetAsText()))
{
return 0;
}
// Simply count the occurrences of \par to get the number of lines.
// Subtract 1 from the actual count because the first \par is not
// actually a line for reasons explained above.
return Regex.Matches(richTextBox.GetAsRTF(), Regex.Escape(@"\par")).Count - 1;
}
}
【讨论】:
int lines = MainTbox.Document.Blocks.Count;
就这么简单。
【讨论】: