Search code examples
c#uwpwindows-10textblockunderline

UWP Underline Textblock with ImageBrush as Foreground does not show the Underline


I am using an ImageBrush as aTextblock Foreground. It works fine but when the Textblock is Underline, the line does not show.

To reproduce. In XAML

<TextBlock x:Name="textBlock" FontSize="80" FontWeight="Bold">
    <Underline>This is my text</Underline>
</TextBlock>

In code behind

Uri uri = new Uri("ms-appx:///Assets/0.png");
BitmapImage bmp = new BitmapImage(uri);
ImageBrush imageBrush = new ImageBrush();
imageBrush.ImageSource = bmp;
this.textBlock.Foreground = imageBrush;

Here's how it looks like with a SolidColorBrush with underline applied

enter image description here

Then when the ImageBrush is applied, the underline is gone

enter image description here

So my question is how do I apply ImageBrush Foreground to an Underline Textblock in UWP?


Solution

  • So my question is how do I apply ImageBrush Foreground to an Underline Textblock in UWP?

    By default, the underline will be removed when the ImageBrush has been applied to TextBlock's Foreground property.

    The workaround is using Border to simulate the underline:

    <Border BorderThickness="0, 0, 0, 2" Height="{Binding ActualHeight, ElementName=textBlock}" Width="{Binding ActualWidth, ElementName=textBlock}">
                <Border.BorderBrush>
                    <ImageBrush ImageSource="Assets/0.jpg" />
                </Border.BorderBrush>
                <TextBlock x:Name="textBlock" FontSize="50" FontWeight="Bold">
                    <TextBlock.Foreground>
                        <ImageBrush ImageSource="Assets/0.jpg" />
                    </TextBlock.Foreground>
                    <Underline><Run Text="This is my text"/></Underline>
                </TextBlock>
            </Border>
    

    enter image description here

    You can create a UserControl/CustomControl to maintain reusability.