簡體   English   中英

WPF中的RichTextBox沒有.Lines屬性?

[英]RichTextBox in WPF does not have an property as .Lines?

是否有相當於WPF中winForms的.Lines?

我目前正在使用這個:

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

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

我知道我參加派對已經很晚了,但是我想出了另一個使用RTF解析的可靠且可重用的解決方案。


理念

在RTF中,每個段落以\\par結尾。 例如,如果您輸入此文本

Lorem ipsum
Foo
Bar

RichTextBox ,它將在內部存儲為(非常非常簡化)

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

因此,簡單地計算那些\\par命令的出現是一種非常可靠的方法。 請注意,除了實際行之外, \\par有1個\\par


用法

感謝擴展方法 ,我提出的解決方案可以像這樣使用:

int lines = myRichTextBox.GetLineCount();

其中myRichTextBoxRichTexBox類的實例。


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;

這很簡單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM