1

I am working on a WinUI 3 application and need to display a line of text where only a portion of the text has a colored background (like a highlight). The requirement is:

The text should wrap exactly like a normal Run inside a TextBlock (i.e., smooth, inline wrapping).

The highlighted part should have a background color behind the text.

I know that Run and Span elements in WinUI 3 do not support a background property.

Using RichTextBlock with InlineUIContainer works for background but breaks the natural text wrapping behavior (especially with longer text).

I want to avoid splitting the text into multiple TextBlocks or losing inline wrapping.

Is there a built-in or custom control approach to achieve this in WinUI 3?

<TextBlock Style="{StaticResource DefaultTextBlockStyle}" FontWeight="{Binding FontWeight}" LineHeight="30" Visibility="{Binding ItemVisibility}">
    <Run Text="{Binding DisplayLabel}" Foreground="{Binding LabelForeground}"/>
    <Run Text="{Binding Value}" Foreground="{Binding ForegroundBrush}" FontWeight="{Binding ValueFontWeight}"/>
</TextBlock>

I have used the app code to display label and value, except the background part everything is working fine.

Expected Out:

enter image description here

Label and Value should be in the same line , Value exceeds the available width it should wrap into nextline and Value should have a background.

1 Answer 1

1

I created the AK.Toolkit.WinUI3.TextBlockEx for this. You can see how it's implemented in the GitHub repo here or you can just install the NuGet package and use it like this:

<StackPanel VerticalAlignment="Center" HorizontalAlignment="Center" Width="155">
    <ak:TextBlockEx
        Text="Label : This is a very very very very long value"
        HighlightingText="This is a very very very very long value"
        TextHighlightBackground="{ThemeResource AccentFillColorDefaultBrush}"
        TextHighlightForeground="{ThemeResource TextControlForeground}" />
</StackPanel>

will render:

sample image

Sign up to request clarification or add additional context in comments.

2 Comments

This solved my use case. Thank you :). I have extended the capabilities for your control by adding support for fontweights(fontweights can be applied to different substrings), and also by allowing comma-separated strings to be passed to the HighlightingText property to apply highlights for multiple substrings. How can I share you this?
In the repo would be great. Feedback is always appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.