繁体   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