Confessions of a .NET Developer!

Show a list of Fonts using WPF

As the headline says, I will be displaying all the available fonts in your system using WPF.

This is how it will look like :

Font Window

Font Window

So the fonts are displayed in the ListBox and the result of selecting it is shown in the TextBox.

This again will be done in XAML itself.
Here is the ListBox.

        <ListBox Margin="20,20,20,77"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"

As you can see, the way ItemsSource is set. Fonts is a Static Class and it has a Property SystemFontFamilies which is a Collection of type FontFamily.

Now what we want is that, the text written in the TextBox should have the Font Family as selected in the ListBox.

        <TextBox Height="27" Margin="20,0,20,35" Name="textBox1" Padding="3" Text="Tarun Kumar Singh" FontSize="13" VerticalAlignment="Bottom"
                 FontFamily="{Binding ElementName=listFonts, Path=SelectedItem}">            

So I have used Binding telling the FontFamily that, bind it to the selected item of the listBox.

If you want to show the Font Family in each of the ListBoxItems, then do this :

        <ListBox Margin="20,20,20,77"
                 ItemsSource="{x:Static Fonts.SystemFontFamilies}"
                    <TextBlock Text="{Binding}" FontFamily="{Binding}"/>

I have specified a DataTemplate for the ListBox. So the items displayed in ListBox will be TextBlocks and Binding its Text and FontFamily taken from the ItemsSource. This {Binding} means that it will take the source from its parent.

So it will look like this :

Font Window2

Font Window2

That’s it!
Happy Coding! 🙂


March 23, 2011 - Posted by | WPF

No comments yet.

Leave a Reply

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

You are commenting using your 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 )


Connecting to %s

%d bloggers like this: