【问题标题】:Coloring certain words in a RichTextBox为 RichTextBox 中的某些单词着色
【发布时间】:2014-05-15 06:46:48
【问题描述】:

我尝试在 RichTextBox 中更改某些单词的颜色,最后我找到了一段代码,对我有很大帮助,但现在我遇到了问题。该代码仅对我的 RichTextBox 中的第一个“NULL”进行着色。

你能帮我找到解决办法吗?

感谢您的帮助!

    private void searchWord()
    {
        String search = "NULL";
        TextPointer text = RTBAuftrag.Document.ContentStart;
        while (true)
        {
            TextPointer next = text.GetNextContextPosition(LogicalDirection.Forward);
            if (next == null)
            {
                break;
            }

            TextRange txt = new TextRange(text, next);

            int indx = txt.Text.IndexOf(search);
            if (indx > 0)
            {
                TextPointer sta = text.GetPositionAtOffset(indx);
                TextPointer end = text.GetPositionAtOffset(indx + search.Length);
                TextRange textR = new TextRange(sta, end);
                textR.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Red));
            }
            text = next;
        }
    }

有人知道这样做的可能方法吗?

【问题讨论】:

    标签: c# colors richtextbox flowdocument words


    【解决方案1】:

    我会自己回答我的问题! 最后我找到了一个很好的解决我的问题的方法。

    我在 code-projekt 上发现了一个非常强大的 UserControl http://www.codeproject.com/Articles/42490/Using-AvalonEdit-WPF-Text-Editor

    我的最终解决方案是:

    将此添加到我的 .xml 中

    xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
    

    还有这个

    <avalonEdit:TextEditor  Visibility="Hidden" x:Name="RTBAuftragNEU" Margin="32,413,243,279" KeyDown="RTBKunde_KeyDown" Panel.ZIndex="1" VerticalScrollBarVisibility="Disabled" HorizontalScrollBarVisibility="Disabled" > </avalonEdit:TextEditor>
    

    然后把它放到我需要的地方。

            using (Stream s = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsultingControls.highlight.xshd"))
            {
                using (XmlTextReader reader = new XmlTextReader(s))
                {
                    RTBAuftragNEU.SyntaxHighlighting = HighlightingLoader.Load(reader, HighlightingManager.Instance);
                }
            }
    

    不要忘记为语法创建 XSHD 文件,您可以在 codeproject 网站上找到完整的教程。

    问候, 弗里多林

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-25
      • 2015-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多