#815 – Filling a ListBox with a List of All Fonts
May 8, 2013 5 Comments
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.
Hi Sean, really nice blog you have with good info, tips and tricks for WPF.
Is there no way to extract all your Tips into a file for better reading, as it’s kind a hard scolling all the way down to #1?
Good question–and a sensible request. I’m hoping to collate everything into a Word doc or PDF and then post it. I’ll look into this and have something soon.
What if WPF can’t draw a font and it crashes an application? How to check it?
I don’t believe that WPF will ever crash your application due to a failure in using a font.
Thanks