WPF RichTextBox,关键字搜索,样式改变,超链接替换,图文混排

RichTextBox 只是一个控件,表示对 FlowDocument 对象执行操作的丰富编辑控件。它所承载的内容由其 Document 属性来呈现。 Document 是一个 FlowDocument 类型. RichTextBox控件允许用户输入和编辑文本的同时提供了比普通的TextBox控件更高级的格式特征。 RichTextBox控件提供了数个有用的特征,你可以在控件中安排文本的格式。要改变文本的格式,必须先选中该文本。只有选中的文本才可以编排字符和段落的格式。有了这些属性,就可以设置文本使用粗体,改变字体的颜色,创建超底稿和子底稿。也可以设置左右缩排或不缩排,从而调整段落的格式。 RichTextBox控件可以打开和保存RTF文件或普通的ASCII文本文件。你可以使用控件的方法(LoadFile和SaveFile)直接读和写文件。RichTextBox控件使用集合支持嵌入的对象。每个嵌入控件中的对象都表示为一个对象。这允许文档中创建的控件可以包含其他控件或文档。例如,可以创建一个包含报表、Microsoft Word文档或任何在系统中注册的其他OLE对象的文档。要在RichTextBox控件中插入对象,可以简单地拖住一个文件(如使用Windows 95的Explorer)或其他应用程序(如Microsoft Word)中所用文件的加亮部分(选择部分),将其直接放到该RichTextBox控件上。RichTextBox控件支持剪贴板和OLE对象的OLE拖放功能。当从剪贴板粘贴对象时,就在当前的插入点插入该对象。如果对象是拖放到控件中,则插入点将跟随鼠标指针位置变动,直到释放开鼠标,然后在鼠标释放处插入对象。要打印RichTextBox控件中的所有或部分文本,使用SelPrint方法。因为RichTextBox控件是数据绑定控件,可以将其与Data控件绑定到Microsoft Access数据库的Binary或Memo数据域,或其他数据库中类似的数据域(如SQL Server中的TEXT数据类型的数据域)。RichTextBox控件支持几乎所有的TextBox控件中的属性、事件和方法,如MaxLength, MultiLine, ScrollBars, SelLength, SelStart和SelText。使用TextBox控件的应用程序很容易改为使用RichTextBox控件。然而,RichTextBox控件并没有普通TextBox控件的64K字符能力的限制。

 用法举例:

<RichTextBox  Background="#E3E3E3"
                              ScrollViewer.VerticalScrollBarVisibility="Hidden"
                              Margin="10,0,0,0"
                              FontFamily="Microsoft YaHei"
                              FontSize="12"
                              IsReadOnly="True"
                              Foreground="#333333"
                              x:Name="richTextBox"
                              BorderThickness="0">
                    <FlowDocument x:Name="richTextBoxFlowDocument"
                                  LineHeight="20" />
                </RichTextBox>

1向文章内容中增加一段文字

    public void AddParagraph(string txtCotent)
        {
            Paragraph p = new Paragraph();  // Paragraph 类似于 html 的 P 标签
            Run r = new Run(txtCotent);      // Run 是一个 Inline 的标签
            p.Inlines.Add(r);
            richTextBoxFlowDocument.Blocks.Add(p);
        }

2 向文章内容中增加一张图片

        public void AddImage(Image imageCotent)
        {
            Paragraph p = new Paragraph();
            InlineUIContainer inline = new InlineUIContainer(imageCotent);
            p.Inlines.Add(inline);
            richTextBoxFlowDocument.Blocks.Add(p);
        }

3   把图片添加到光标位置

        private void AddImageInPosin(string filepath)
        {
            Image img = new Image();
            BitmapImage bImg = new BitmapImage();
            img.IsEnabled = true;
            bImg.BeginInit();
            bImg.UriSource = new Uri(filepath, UriKind.Relative);
            bImg.EndInit();
            img.Source = bImg;
            //// 调整图片大小
            //if (bImg.Height > 100 || bImg.Width > 100)
            //{
            //    img.Height = bImg.Height * 0.2;
            //    img.Width = bImg.Width * 0.2;
            //}
            img.Height = 50;
            img.Stretch = Stretch.Uniform;  //图片缩放模式
            new InlineUIContainer(img, richTextBox.Selection.Start); //插入图片到选定位置
        }

4 把文章中指定关键字替换成超链接

/// <summary>
        /// 设置热点词为超链接
        /// </summary>
        /// <param name="key">热点词</param>
        /// <param name="foreground">热点词字体颜色</param>
        public void ConvertKeyToHyperLink(string key, SolidColorBrush foreground)
        {
            m_TextList = new List<TextRange>();
            //设置文字指针为Document初始位置           
            //richBox.Document.FlowDirection           
            TextPointer position = richTextBox.Document.ContentStart;
            while (position != null)
            {
                //向前搜索,需要内容为Text       
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    //拿出Run的Text        
                    string text = position.GetTextInRun(LogicalDirection.Forward);
                    //可能包含多个keyword,做遍历查找           
                    int index = 0;
                    index = text.IndexOf(key, 0);
                    if (index != -1)
                    {
                        TextPointer start = position.GetPositionAtOffset(index);
                        TextPointer end = start.GetPositionAtOffset(key.Length);
                        // m_TextList.Add(new TextRange(start, end));
                        linke(new TextRange(start, end), key, foreground);
                    }
                }
                //文字指针向前偏移   
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }
        }

  private void linke(TextRange tp, string key, SolidColorBrush foreground)
        {
            TextRange tr = new TextRange(tp.Start, tp.End);
            Hyperlink hlink = new Hyperlink(tr.Start, tr.End);
            hlink.Tag = key;
            hlink.Foreground = foreground;
              
            hlink.FontFamily = new FontFamily("Microsoft YaHei");
            hlink.FontSize = 12;
            hlink.Cursor = Cursors.Hand;
            hlink.MouseDown += hyperlink_MouseDown;
        }

5 后台向文章中新增一个超链接

private void AddLink()
        {
            Hyperlink hyperlink = new Hyperlink();
            hyperlink.Foreground = new SolidColorBrush(Colors.Blue);
            hyperlink.ForceCursor = true;
            hyperlink.Cursor = Cursors.Hand;

            hyperlink.Inlines.Add("后台添加的超链接");
            //hyperlink.NavigateUri = new Uri("http://www.baidu.com",UriKind.Absolute); 
            hyperlink.MouseDown += hyperlink_MouseDown;
            Paragraph p = new Paragraph();
            p.Inlines.Add(hyperlink);
            richTextBoxFlowDocument.Blocks.Add(p);
        }

6 改变用户搜索的关键词的样式,并支持当前选中的高亮

        /// <summary>
        /// 改变在文章中用户搜索的关键字的字体颜色
        /// </summary>
        /// <param name="keyword"></param>
        public void ChangeSeachKeyWordsColor(string keyword)
        {
            ChangeColorWithResout(keyword);
        }

        /// <summary>
        /// 改变关键字的字体颜色
        /// </summary>
        /// <param name="keyword">用户搜索关键字</param>
        /// <returns></returns>
        private List<TextRange> ChangeColorWithResout(string keyword)
        {
            if (!string.IsNullOrEmpty(m_ProSearchkey))
            {
                ChangeColor(CommonColorsHelp.DefaultFontColor, m_ProSearchkey);
                ReSetBackGroundAll();
            }
            m_ProSearchkey = keyword;

            return ChangeColor(CommonColorsHelp.KeyFontColor, keyword);
        }



        /// <summary>
        /// 设置背景色
        /// </summary>
        /// <param name="l"></param>
        /// <param name="textRange"></param>
        public void SetBackGround(Color l, TextRange textRange)
        {
            textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(l));
            textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(CommonColorsHelp.SelectedKeyFontColor));
        }
        /// <summary>
        /// 重新设置背景色
        /// </summary>
        /// <param name="textRange">关键字的的TextRange</param>
        /// <param name="isCurrKeyWord">是否是当前的关键字</param>
        public void ReSetBackGround(TextRange textRange, bool isCurrKeyWord)
        {
            textRange.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(CommonColorsHelp.DefaultBackGroundColor));
            if (isCurrKeyWord)
            {
                textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(CommonColorsHelp.KeyFontColor));
            }
            else
            {
                textRange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(CommonColorsHelp.DefaultFontColor));
            }

        }

        /// <summary>
        /// 上一处
        /// </summary>
        public void SetUpBackGround()
        {
            if (m_TextList != null && m_TextList.Count > 0)
            {
                ReSetBackGround(m_TextList[currNumber], true);
                currNumber--;
                if (currNumber < 0)
                {
                    currNumber = m_TextList.Count - 1;
                }
                SetBackGround(CommonColorsHelp.SelectedKeyBackGroundColor, m_TextList[currNumber]);
            }

        }
        /// <summary>
        /// 下一处
        /// </summary>
        public void SetDownBackGround()
        {
            if (m_TextList != null && m_TextList.Count > 0)
            {
                ReSetBackGround(m_TextList[currNumber], true);
                currNumber++;
                if (currNumber >= m_TextList.Count)
                {
                    currNumber = 0;
                }
                SetBackGround(CommonColorsHelp.SelectedKeyBackGroundColor, m_TextList[currNumber]);
            }
        }
/// <summary>
        /// 改变关键字的具体实现
        /// </summary>
        /// <param name="l"></param>
        /// <param name="richTextBox1"></param>
        /// <param name="selectLength"></param>
        /// <param name="tpStart"></param>
        /// <param name="tpEnd"></param>
        /// <returns></returns>
        private TextPointer selecta(Color l, RichTextBox richTextBox1, int selectLength, TextPointer tpStart, TextPointer tpEnd)
        {
            TextRange range = richTextBox1.Selection;
            range.Select(tpStart, tpEnd);
            //高亮选择
            range.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(l));
            return tpEnd.GetNextContextPosition(LogicalDirection.Forward);
        }
        /// <summary>
        /// 把所有背景恢复到默认
        /// </summary>
        private void ReSetBackGroundAll()
        {
            if (m_TextList != null)
            {
                foreach (TextRange textRange in m_TextList)
                {
                    ReSetBackGround(textRange, false);
                }
            }
        }
/// <summary>
        /// 当前第几处关键字被选中
        /// </summary>
        private int currNumber = 0;
        /// <summary>
        /// 改变关键字字体颜色
        /// </summary>
        /// <param name="l">颜色</param>
        /// <param name="keyword">关键字</param>
        /// <returns></returns>
        private List<TextRange> ChangeColor(Color l, string keyword)
        {
            m_TextList = new List<TextRange>();
            //设置文字指针为Document初始位置           
            //richBox.Document.FlowDirection           
            TextPointer position = richTextBox.Document.ContentStart;
            while (position != null)
            {
                //向前搜索,需要内容为Text       
                if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text)
                {
                    //拿出Run的Text        
                    string text = position.GetTextInRun(LogicalDirection.Forward);
                    //可能包含多个keyword,做遍历查找           
                    int index = 0;
                    index = text.IndexOf(keyword, 0);
                    if (index != -1)
                    {
                        TextPointer start = position.GetPositionAtOffset(index);
                        TextPointer end = start.GetPositionAtOffset(keyword.Length);
                        m_TextList.Add(new TextRange(start, end));
                        position = selecta(l, richTextBox, keyword.Length, start, end);
                    }
                }
                //文字指针向前偏移   
                position = position.GetNextContextPosition(LogicalDirection.Forward);
            }

            if (m_TextList != null && m_TextList.Count > 0)
            {
                //重置
                currNumber = 0;
                SetBackGround(CommonColorsHelp.SelectedKeyBackGroundColor, m_TextList[currNumber]);
            }

            return m_TextList;
        }
        /// <summary>
        /// 当前关键字共搜索出的结果集合
        /// </summary>
        private List<TextRange> m_TextList;

 

 

转载于:https://www.cnblogs.com/shanranlei/p/3635317.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要改变WPF RichTextBox的颜色,需要使用Selection和TextRange类的属性和方法。可以使用SelectionStart和SelectionLength属性来选择RichTextBox的一部分文本。可以使用Foreground属性来设置文本的前景色(即文本颜色)。可以使用Background属性来设置文本的背景色。还可以使用FontFamily、FontSize和FontStyle属性来设置文本的字体、大小和风格。最后,可以使用TextRange类的ApplyPropertyValue方法来将这些属性应用于选择的文本。 ### 回答2: WPFRichTextBox控件是一个强大而灵活的文本编辑器,可以实现丰富的文本编辑功能。在控制文本中的颜色方面,RichTextBox提供了多种方式来实现。 首先简单介绍一个基本的设置颜色的方法: 1. 通过Selection对象设置:使用RichTextBox控件的Selection属性(Selection属性表示当前所选内容),可以轻松地设置选中文本的颜色。例如,以下代码将设置选中文本为红色: ``` richTextBox1.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red); ``` 2. 通过Run对象设置:使用RichTextBox控件的Inline属性(Inline属性表示RichTextBox控件中包含的每一个文本单元),可以通过建立Run对象设置选中文本的颜色。例如,以下代码将设置选中文本为红色: ``` Run myRun = new Run("要设置为红色的文本"); myRun.Foreground = Brushes.Red; richTextBox1.Document.Blocks.Add(new Paragraph(myRun)); ``` 我们可以通过Run对象的Foreground属性来设置选中文本的颜色,并通过Document的Blocks属性将Run添加到RichTextBox中。 3. 通过样式设置:WPFRichTextBox控件支持样式。通过定义一个控件样式可以快速设置文本的外观和布局。这样,我们可以通过定义样式来设置文本的颜色。例如,以下代码定义了一个样式,其中的Foreground属性设置了文本的颜色: ``` <Style x:Key="Style1" TargetType="Run"> <Setter Property="Foreground" Value="Blue"/> </Style> ``` 这个样式包括了一个名为Style1的属性和一个目标类型为Run类型的Setter。在定义好Style1后,我们可以通过给选定文本设置这个样式改变文本的颜色: ``` Run myRun = new Run("要设置为蓝色的文本"); myRun.Style = (Style)this.Resources["Style1"]; richTextBox1.Document.Blocks.Add(new Paragraph(myRun)); ``` 以上是三种设置文本颜色的方式,可以根据实际需求选择不同的方法来实现改变文本颜色的功能。在实际应用中,我们也可以根据需要将它们进行组合,产生更加丰富的效果,以满足用户的需求。 ### 回答3: WPF RichTextBox是一个非常强大的控件,可以用于显示和编辑富文本内容。它提供了许多功能,包括改变颜色。 改变WPF RichTextBox中文本颜色的方式实际上非常简单。你可以使用Selection对象,将选定的文本颜色设置为所需的颜色。 以下是一个简单的示例,演示如何将RichTextBox中的文本颜色设置为红色: ```csharp private void ChangeTextColor() { // 获取RichTextBox的Selection TextSelection selection = myRichTextBox.Selection; // 设置选定文本的字体颜色为红色 selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red); } ``` 这里我们首先获取RichTextBox的Selection对象,然后将选定文本的字体颜色设置为红色。 我们还可以使用类似的方式设置选定文本的背景颜色。示例代码如下: ```csharp private void ChangeBackgroundColor() { // 获取RichTextBox的Selection TextSelection selection = myRichTextBox.Selection; // 设置选定文本的背景颜色为黄色 selection.ApplyPropertyValue(TextElement.BackgroundProperty, Brushes.Yellow); } ``` 我们还可以通过代码设置整个RichTextBox的默认字体颜色或背景颜色。代码如下: ```csharp // 设置整个RichTextBox的默认字体颜色 myRichTextBox.Foreground = Brushes.Red; // 设置整个RichTextBox的默认背景颜色 myRichTextBox.Background = Brushes.Yellow; ``` 总的来说,WPF RichTextBox提供了很多方便的方法来改变文本的颜色。它非常易于使用,可以帮助我们快速创建具有丰富文本功能的应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值