WPF Paragraph获取或修改文本内容

一、说明

Paragraph继承自Block,Block继承自TextElement,在TextElement中

        //
        // 摘要:
        //     获取表示元素中内容末尾的 System.Windows.Documents.TextPointer。
        //
        // 返回结果:
        //     表示 System.Windows.Documents.TextElement 中内容末尾的 System.Windows.Documents.TextPointer。
        public TextPointer ContentEnd { get; }
        //
        // 摘要:
        //     获取表示元素中内容开头的 System.Windows.Documents.TextPointer。
        //
        // 返回结果:
        //     表示 System.Windows.Documents.TextElement 中内容开头的 System.Windows.Documents.TextPointerContext。
        public TextPointer ContentStart { get; }

通过获取ContentStart点和ContentEnd点之间的内容,获取段落内容:TextRand.Text

    //
    // 摘要:
    //     表示两个 System.Windows.Documents.TextPointer 位置之间的所选内容。
    public class TextRange : ITextRange
    {
        // 参数:
        //   position1:
        //     标记用于组成新 System.Windows.Documents.TextRange 的所选内容的一端的固定定位点位置。
        //
        //   position2:
        //     标记用于组成新 System.Windows.Documents.TextRange 的所选内容的另一端的可移动位置。
        public TextRange(TextPointer position1, TextPointer position2);

实例代码:

//获取段落部分的内容
Paragraph p = doc.FindName("one") as Paragraph;
TextRange range = new TextRange(p.ContentStart, p.ContentEnd);
string str = range.Text;
MessageBox.Show(str);
//修改段落内容
p.Inlines.Clear();
p.Inlines.Add(new Run("天涯共此时"));
原文地址:https://www.cnblogs.com/tianma3798/p/5929233.html