How to highlight certain part of text in listbox with one colour when the background is in different colour in WPF?

77 Views Asked by At

I have these functions that will look into highlighting text in listbox. It works but now I am struggling with the part which will highlight a certain part of the text. For example, when you have "Hello World to WPF" and you want to highlight the whole text say light blue and "World" with any other colour. What changes do I need to make here?

private async void WriteHighlighttexts(ListBox Datalabel, Dictionary<long, List<string[]>> arraylog)
{
    Datalabel.Items.Clear();

    foreach (KeyValuePair<long, List<string[]>> pair in arraylog)
    {
        List<string[]> logwritehigh = pair.Value;

        // Set autoScroll to false before updating the content
        bool autoScroll = false;

        foreach (string[] pair2 in logwritehigh)
        {
            string Linecolour = pair2[0];
            await Task.Run(() =>
            {
                // Run the code in the background thread

                Dispatcher.Invoke(() =>
                {
                    // Append the line to the ListBox
                    ListBoxItem listBoxItem = new ListBoxItem();
                    listBoxItem.Content = pair2[1];
                    Datalabel.Items.Add(listBoxItem);

                    //// Ensure the text is fully updated before proceeding with highlighting
                    //Task.Delay(5).Wait();

                    // Highlight the entire line with the specified color
                    HighlightLine(listBoxItem, Linecolour);
                });
            });

            await Task.Delay(15);

            // Restore autoScroll to true after updating the content
            autoScroll = true;

            // Scroll to the end of the RichTextBox if autoScroll is enabled
            if (autoScroll)
            {
                Datalabel.ScrollIntoView(Datalabel.Items[Datalabel.Items.Count - 1]);
            }
        }
    }
}

private void HighlightLine(ListBoxItem listBoxItem, string color)
{
    System.Drawing.Color lineColor = ColorTranslator.FromHtml(color);
    SolidColorBrush brush = new SolidColorBrush(System.Windows.Media.Color.FromArgb(lineColor.A, lineColor.R, lineColor.G, lineColor.B));

    listBoxItem.Background = brush;
}
1

There are 1 best solutions below

7
mm8 On

Replace the string with a TextBlock that has Inline elements that you can style individually, e.g.:

// Append the line to the ListBox
ListBoxItem listBoxItem = new ListBoxItem();
string[] words = "Hello World to WPF".Split(' ');
TextBlock textBlock = new TextBlock();
if (words != null)
{
    foreach (string word in words)
    {
        Inline inline = new Run { Text = word };
        textBlock.Inlines.Add(inline);
        if (word == "World")
            inline.Background = Brushes.Yellow;
    }
}
listBoxItem.Content = textBlock;
Datalabel.Items.Add(listBoxItem);

HighlightLine(listBoxItem, Linecolour);