WPF Paragraph获取或修改文本内容

本文介绍如何在WPF中利用TextPointer和TextRange类获取与修改TextElement内容,包括创建TextRange对象来选取指定范围的文字,并演示了通过获取段落开始和结束点来读取和更新段落内容的具体步骤。

一、说明

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值