How to enumerate all installed fonts on UWP

In this article we’ll show you how a UWP app can detect and enumerate all the installed fonts on the device, and how to apply a selected font to a UI element.

It’s all extremely easy – if you know which NuGet package to use:

Win2D_UWP

Win2D is a Windows Runtime API wrapper on Direct2D that is specialized in rendering 2D graphics using hardware acceleration.

Win2D comes with API calls and XAML helper controls for:

  • manipulating and rendering bitmaps,
  • manipulating vector graphics,
  • applying color effects and filters,
  • converting text to geometry, et cetera.

If you want to dive deeper into Win2D then checkout these features and UWP samples.

Once you’re referencing the Win2D.UWP NuGet package, enumerating the installed fonts on the device is literally a one-liner. Just call the GetSystemFontFamilies on the CanvasTextFormat class. It returns the (localized!) font names as an array of strings:

public List<string> Fonts
{
    get
    {
        return CanvasTextFormat.GetSystemFontFamilies().OrderBy(f => f).ToList();
    }
}

To display these in a ComboBox, assign the list to its ItemsSource:

<ComboBox x:Name="FontsCombo"
            ItemsSource="{x:Bind Fonts}"
            SelectionChanged="FontsCombo_SelectionChanged">
    <!---... -->
</ComboBox>

When the ComboBox’s selection changes, we update the font of a TextBox. Provide the font name string to the FontFamily constructor to set the FontFamily dependency property:

private void FontsCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    TextEditor.FontFamily = new FontFamily(FontsCombo.SelectedValue.ToString());
}

In the ComboBox’s item template, I used x:Bind to provide both the FontFamily and Text for the TextBlock (don’t forget to specify the item type with x:DataType).

<ComboBox.ItemTemplate>
    <DataTemplate x:DataType="x:String">
        <TextBlock FontFamily="{x:Bind}"
                    Text="{x:Bind}" />
    </DataTemplate>
</ComboBox.ItemTemplate>

Done!

Here’s how all of this looks like at runtime:

ScreenShot

The sample app lives here on GitHub.

Enjoy!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s