#815 – Filling a ListBox with a List of All Fonts

The static Fonts.SystemFontFamilies property contains list of all fonts installed on your system.  Each element in the collection referenced by this property is a FontFamily object.

You can build a list of all fonts by binding a ListBox to this collection.  The example below uses a CollectionViewSource element, bound to SystemFontFamilies, which allows us to sort the items in the collection.  We then bind the ListBox to this collection.

<Window
        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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
        x:Class="WpfApplication2.MainWindow"
        Width="300" Height="200"
        Title="Display a List of Fonts">

    <Window.Resources>
        <CollectionViewSource x:Key="allFonts"
                              Source="{Binding Source={x:Static Fonts.SystemFontFamilies}}">
            <CollectionViewSource.SortDescriptions>
                <scm:SortDescription PropertyName="Source"/>
            </CollectionViewSource.SortDescriptions>
        </CollectionViewSource>
    </Window.Resources>

    <Grid>
        <ListBox ItemsSource="{Binding Source={StaticResource allFonts}}"
                 Margin="5" ScrollViewer.VerticalScrollBarVisibility="Auto">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding}"
                               FontFamily="{Binding}"
                               FontSize="14"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

We display each item in the list using the appropriate font by using a data template and setting the FontFamily property of a TextBlock.

815-001