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:
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.
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: