Question

In Xamarin.Forms I am using a Label and trying to set a Font.

The following code works:-

Label label1 = new Label();
label1.Font = Font.SystemFontOfSize(10);

However trying to specify the Font Attributes such like:-

Label label1 = new Label();
label1.Font = Font.SystemFontOfSize(10, FontAttributes.Bold);

is preventing the ContentPage from rendering with an exception.

There is a Font.BoldSystemFontOfSize(), which could be used, however this is meant to be deprecated, so I am trying to now use Font.SystemOfSize instead.

How is it done using this?

Was it helpful?

Solution

Here's a piece of code that works in my project:

new Label {
   Text = "text goes here",
   Font = Font.SystemFontOfSize (NamedSize.Medium)
              .WithAttributes (FontAttributes.Bold),
}

This allows you to not specify a certain font size and instead use the font size used by default for the label

OTHER TIPS

I guess I'm late for answering. But still I'd like to mention that, this can be done using XAML now. The following XAML will give the desired output.

<Label Text="Hello Label" FontSize="20" FontAttributes="Bold"/>

You can refer to the following link to more about working with Fonts in Xamarin.Forms.

Working With Fonts in XForms

Following documentation Xamarin.Forms - Working with Fonts, you should use following code:

Label label1 = Font.SystemFontOfSize (10, FontAttributes.Bold | FontAttributes.Italic)

Same page states that BoldSystemFontOfSize is deprecated.

If you need more than one place where the bold font is required then you will be better of creating a style. Either globally in the app.cs with or without a key or in the page level. You can set all the properties you want to the appropriate values and use wherever you want.

For reference check this page

I had a similar situation where the FontAttributes="Bold" of a Label inside a DataTemplate for a ListView were not rendered as Bold in iOS. Android rendered fine.

When not within a DataTemplate, the Bold Label rendered correctly.

The cause was that the default font did not have a Bold available on iOS. When I added a Font="Arial" to the Label, it correctly rendered the Bold in iOS.

I'm sharing this in case someone else has this same issue.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top