How to highlight the word(s) with bold in text block for specified keyword using the attached property

后端 未结 2 1272
感动是毒
感动是毒 2021-01-23 07:46

The objective is to bold the word(s) of text in Textblock with matching input keyword.

For example: Stackoverflow is a very helpful, keep using Stackoverflow to sharpen

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-23 08:41

    Whether you want to modify a TextBlock FontWeight attribute or another display property, I've written the following static method and found it very useful. (Note: The method illustrates highlighting text by modifying the Foreground property. The same principle can be used for any other TextBlock display attribute.)

        static Brush DefaultHighlight = new SolidColorBrush(Colors.Red);
    
        public static void SetTextAndHighlightSubstring(this TextBlock targetTextBlock, string sourceText, string subString, Brush highlight = null)
        {
            if (targetTextBlock == null || String.IsNullOrEmpty(sourceText) || String.IsNullOrEmpty(subString))
                return;
            targetTextBlock.Text = "";
            var subStringPosition = sourceText.ToUpper().IndexOf(subString);
            if (subStringPosition == -1)
            {
                targetTextBlock.Inlines.Add(new Run { Text = sourceText });
                return;
            }
            var subStringLength = subString.Length;
            var header = sourceText.Substring(0, subStringPosition);
            subString = sourceText.Substring(subStringPosition, subStringLength);
            var trailerLength = sourceText.Length - (subStringPosition + subStringLength);
            var trailer = sourceText.Substring(subStringPosition + subStringLength, trailerLength);
            targetTextBlock.Inlines.Add(new Run { Text = header });
            targetTextBlock.Inlines.Add(new Run { Text = subString, Foreground = highlight ?? DefaultHighlight });
            targetTextBlock.Inlines.Add(new Run { Text = trailer });
        }
    

    You can call this method using the TextBlock extension syntax like so:

    TextBlockTitle.SetTextAndHighlightSubstring(_categoryItem.ItemText, _searchText);
    

    In this example, the following display resulted:

提交回复
热议问题