自动突出显示 TextBox 或 RichTextBox 中的部分文本

Automatic highlighting a part of the text in a TextBox or RichTextBox

是否可以在不选择这部分文本的情况下突出显示文本的一部分,最好在文本框或富文本框中使用不同的颜色?事实上,我的意思是,文本的一部分被另一种颜色突出显示,该颜色不同于为文本选择分配的颜色。为澄清起见,我附上了一张显示此行为的图片。 (图片来自网站,不是WPF)。 粗体和深绿色部分是刚刚突出显示的文本,灰色区域是选中的部分。

使用 RichTextBox 元素允许更多样式选项,据我所知,这些选项不适用于常规 TextBox 元素。

这是我创建的一种方法:

// Generate example content
FlowDocument doc = new FlowDocument();

Run runStart = new Run("This is an example of ");
Run runHighlight = new Run("text highlighting in WPF");
Run runEnd = new Run(" using the RichTextBox element.");

// Apply highlight style
runHighlight.FontWeight = FontWeights.Bold;
runHighlight.Background = Brushes.LightGreen;

// Create paragraph
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(runStart);
paragraph.Inlines.Add(runHighlight);
paragraph.Inlines.Add(runEnd);

// Add the paragraph to the FlowDocument
doc.Blocks.Add(paragraph);

// Apply to RichTextBox
YourRichTextBoxHere.Document = doc;

View Screenshot

我发现这篇文章很有帮助。

Highlight Searched Text in WPF ListView

虽然这篇文章是关于在 ListView 中突出显示搜索到的文本,但我已经在我自己的代码中轻松地对其进行了调整,以便与几乎所有控件一起使用。

从您传入的控件开始,它将递归查找 TextBlocks 并找到您想要的文本,将其提取为内联,并将其更改为 Background / Foreground属性。

如果需要,您可以轻松地将代码调整为一种行为。

这是一个例子:

private void HighlightText(object controlToHighlight, string textToHighlight)
{
    if (controlToHighlight == null) return;

    if (controlToHighlight is TextBlock tb)
    {
        var regex = new Regex("(" + textToHighlight + ")", RegexOptions.IgnoreCase);

        if (textToHighlight.Length == 0)
        {
            var str = tb.Text;
            tb.Inlines.Clear();
            tb.Inlines.Add(str);
            return;
        }

        var substrings = regex.Split(tb.Text);
        tb.Inlines.Clear();

        foreach (var item in substrings)
        {
            if (regex.Match(item).Success)
            {
                var run = new Run(item)
                {
                    Background = (SolidColorBrush) new BrushConverter().ConvertFrom("#FFFFF45E")
                };

                tb.Inlines.Add(run);                            
            }
            else
            {
                tb.Inlines.Add(item);
            }
        }
    }
    else
    {
        if (!(controlToHighlight is DependencyObject dependencyObject)) return;

        for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
        {
            HighlightText(VisualTreeHelper.GetChild(dependencyObject, i), textToHighlight);
        }
    }
}

希望对您有所帮助!