RichTextBox в WPF не имеет свойства как .Lines? - PullRequest
7 голосов
/ 25 января 2012

есть ли эквивалент .Lines winForms в WPF?

Я сейчас использую это:

var textRange = new TextRange(TextInput.Document.ContentStart, TextInput.Document.ContentEnd);
string[] lines = textRange.Text.Split('\n');

Ответы [ 3 ]

3 голосов
/ 25 января 2012

RichTextBox - это тип FlowDocument, который не имеет свойства Lines.То, что вы делаете, кажется хорошим решением.Возможно, вы захотите использовать IndexOf вместо split.

Вы также можете добавить метод расширения, подобный предложенному в статье:

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;
}
0 голосов
/ 31 марта 2019
int lines = MainTbox.Document.Blocks.Count;

это так просто.

0 голосов
/ 02 июня 2018

Я знаю, что очень опаздываю на вечеринку, но я нашел другое надежное и многоразовое решение с использованием RTF-анализа.


Идея

В RTF каждый абзац заканчивается \par.Так, например, если вы введете этот текст

Lorem ipsum
Foo
Bar

в RichTextBox, он будет внутренне сохранен как (очень очень упрощенный)

\par
Lorem ipsum\par
Foo\par
Bar\par

, следовательно, это довольно надежный методпросто посчитать вхождения этих \par команд.Обратите внимание, что всегда на 1 \par больше, чем есть фактические строки.


Использование

Благодаря методам расширения мое предлагаемое решение может быть простоиспользуется следующим образом:

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;
    }
}
...