RichTextBox in WPF does not have an property as .Lines?
RichTextBox is a FlowDocument type and that does not have a Lines property. What you are doing seems like a good solution. You may want to use IndexOf instead of split.
You can also add an extension method like the article suggests:
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;
}
I know I'm very late to the party, but I came up with another reliable and reusable solution using RTF parsing.
Idea
In RTF, every paragraph ends with a \par
. So e.g. if you enter this text
Lorem ipsum
Foo
Bar
in a RichTextBox
, it will internally be stored as (very very simplified)
\par
Lorem ipsum\par
Foo\par
Bar\par
therefore, it is a quite reliable method to simply count the occurrences of those \par
commands. Note though that there is always 1 more \par
than there are actual lines.
Usage
Thanks to extension methods, my proposed solution can simply be used like this:
int lines = myRichTextBox.GetLineCount();
where myRichTextBox
is an instance of the RichTexBox
class.
Code
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;
}
}