If you are writing an application that uses font you will find this post very useful. Making a font selecting ComboBox that shows a preview of the fonts in WPF is very easy, here is how to do it:
First we will have to create the ComboBox Code, this is a regular ComboBox we have all useda million times but still:
1: <ComboBox Width="100" Height="30" x:Name="FontSelector">
2: <ComboBox.ItemTemplate>
3: <DataTemplate>
4: <TextBlock Text="{Binding}" FontFamily="{Binding}"/>
5: </DataTemplate>
6: </ComboBox.ItemTemplate>
7: </ComboBox>
We all know that a TextBlock has a FontFamily property, well, now we are going to “abuse” it. Now it is time to set the ComboBox ItemSource:
1: private void Window_Loaded(object sender, RoutedEventArgs e)
2: {
3: FontSelector.ItemsSource = Fonts.SystemFontFamilies;
4: }
That’s it, the result is this:
How did this work? Lets check out the Binded object in the ComboBox. The object is of type FontFamily, and has a “Source” property which is the name of the font. The TextBlock Text and FontFamily properties are actually binded to the same “Source” property but make different use of it. The Text Property shows the name of the font while the FontFamily uses the name of the font to apply the appropriate style to the text.
Enjoy
Amit
We pay for user submitted tutorials and articles that we publish. Anyone can send in a contribution
Learn More
contrapunctus Said on May 4, 2008 :
isnt it possible to do this without any codebehind? i.e. with pure xaml?
Shahar Y Said on May 4, 2008 :
Hi contrapunctus,
Yes you can, just add to ComboBox the next attribute (in XAML): ItemsSource=”{x:Static Fonts.SystemFontFamilies}”.
This was the first thing that came to our mind, you are right, its much nicer in XAML.
Amit & ShaharY
Galaxia Said on Feb 13, 2009 :
I dont think you can do this in the latest silverlight with v3.5.
unless you have a more complete code sample.
Galaxia Said on Feb 13, 2009 :
I get a static not supported error using the below code.
Galaxia Said on Feb 13, 2009 :
we cant post code?…what a fab code forum…lol