The font my client wants me to use looks really squished together when it wraps to a second line. To counter this, I have added default property setting to all of my labels to make the LineHeight “1.3”.
<Style TargetType="Label" ApplyToDerivedTypes="True">
<Setter Property="LineHeight" Value="1.3" />
</Style>
The problem is, this LineHeight doesn’t seem to work when the Label’s TextType
is set to ‘Html’.
I’m currently Binding my Label’s text to an HTML string in my View Model. I used the following text with an inline style to set the line-height, but it had no effect.
vm.Notes = "<span style="line-height:2">This is <strong style="color: red;">html</strong> text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec faucibus sem.</div>";
<Label Text="{Binding Notes}" TextType="Html" />
When I run this code, I can see that the word “html” is bolded, but it is not red, and the line-height style did not work (text is still too close when it wraps).
If I can’t use the Label’s LineHeight
property, and I can’t use an inline html style, is there any other workaround to this problem other than using a different font?
So far, I have only tried this on Android. The font is SangBleuSunrise-Regular
.
1
Android supports only a subset of HTML tags, focusing on basic styling and formatting for block level elements such as <span>
and <p>
. You can see the doc: Display HTML.
For but it is not red
, you can add a span
to achieve:
ll.Text = "<span style="line-height:2">This is <span style="color: red;"><strong>html</strong></span> text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec faucibus sem.</div>";
For the line-height style did not work
,
you can use android platform code to achieve it:
Declare a MyLabel class:
namespace MauiApp1
{
internal class MyLabel : Label
{
}
}
Then use it in MainPage:
<ContentPage ....
xmlns:control="clr-namespace:MauiApp1"
x:Class="MauiApp1.MainPage">
.......
<Label
Text="Hello, World!"
...../>
<Label
Text="Welcome to
.NET Multi-platform App UI"
....../>
<control:MyLabel x:Name="ll"
TextType="Html"/>
public MainPage()
{
InitializeComponent();
ll.Text = "<span style="line-height:0.7">This is <span style="color: red;"><strong>html</strong></span> text. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec faucibus sem.</div>";
ModifyLabel();
}
void ModifyLabel()
{
Microsoft.Maui.Handlers.LabelHandler.Mapper.AppendToMapping("MyCustomization", (handler, view) =>
{
if (view is MyLabel)
{
#if ANDROID
handler.PlatformView.SetLineSpacing(0, 0.5f);
#endif
}
});
}
Here is the effect.
1