How to display Bootstrap icons in Xamarin?

Viewed 262

I'm new to Xamarin development, but try to be exact.

Using Visual Studio 2022, with Xamarin version 17.0.0.182 (as displayed in VS About).

Found this great article on how to use Bootstrap icons, but it seems to be out of date. When I followed the steps and provided hex codes for the characters, I didn't get the expected glyiphs.

1 Answers

I found that

  • new Xamarin needs new methods,
  • new Bootstrap fonts need new ways.

Here they are.

1.) Get the font from the Bootstrap github repo at https://github.com/twbs/icons

Go to releases (https://github.com/twbs/icons/releases), choose latest, scroll down to Assets, download the bootstrap-icons-x.x.x.xip file.

Unzip it, and find fonts/bootstrap-icons.woff.

Not something you can use in Xamarin right away :-(

2.) Convert the woff file to ttf

I googled for a converter and used https://cloudconvert.com/woff-to-ttf

Now you have the ttf you need :-)

3.) Now follow the current Xamarin method of adding a font to your app.

The process is described here: https://devblogs.microsoft.com/xamarin/embedded-fonts-xamarin-forms/

In short:

  • add the ttf file to the shared Xamarin project, Embedded Resources / Fonts
  • change file properties / Build Action to "Embedded resource"
  • register the font by adding a line to the end of Assemblyinfo.cs: [assembly: ExportFont("bootstrap-icons.ttf", Alias = "Bootstrap")]

4.) Use it in xaml like

   <Label FontFamily="Bootstrap" Text="&#xf62c;"/>

to display a magnifying glass.

You may also define a Label style, but I'll skip that for now.

4/b.) To use it in xaml via binding

Oh, if things were easy...

When using a binding to display a glyph, there's one more hoop to jump, thanks to these guys for the solution: Using data binding, how do I bind text which contains emojis to a label and have it display correctly?

So, in xaml:

  <!-- set BindingContext to MyViewModel -->
  <Label FontFamily="Bootstrap" Text="{Binding StateIconName}" />

in your MyViewModel:

  public string StateIconName
  {
      get => WebUtility.HtmlDecode("&#xf282;");
  }

5.) To browse available glyphs (icons)

Open the overview page: https://icons.getbootstrap.com/

6.) To find the unicode character code, also referred to as "Unicode HTML Entity"

Related