Search code examples
c#fontscomboboxwinui-3

How to display all installed fonts in a ComboBox


I need to display all the user's installed fonts in a WinUI 3 ComboBox. I'm using this code:

<ComboBox x:Name="FontComboBox" ItemsSource="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Source}" FontFamily="{Binding Source}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

But this causes the error:

The type 'x:Static' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built.

Not sure what an assembly reference is.

What would I do to fix this?


Solution

  • AFAIK, WinUI 3 doesn't support x:Static.

    So, let me show you another way to achieve this using the Win2D NuGet package.

    <Page
        x:Class="FontFamiliesExample.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="using:FontFamiliesExample"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:win2d="using:Microsoft.Graphics.Canvas.Text"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"
        mc:Ignorable="d">
    
        <StackPanel>
            <ComboBox ItemsSource="{x:Bind win2d:CanvasTextFormat.GetSystemFontFamilies()}" />
        </StackPanel>
    
    </Page>