Apr
15th | 2008

How to Create a Word Like Font Selection in WPF ComboBox

Filed under C#, WPF | Posted by Amit

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:

Font Select ComboBox

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

Tags: , , , , , , , ,

4 Responses to “How to Create a Word Like Font Selection in WPF ComboBox”



  1. By contrapunctus on May 4, 2008 | Reply

    isnt it possible to do this without any codebehind? i.e. with pure xaml?

  2. By Shahar Y on May 4, 2008 | Reply

    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

  1. 2 Trackback(s)

  2. Apr 21, 2008: Weekly Links: ASP.NET MVC, Silverlight 2, WPF, WCF… | Code-Inside Blog International
  3. Apr 21, 2008: Wöchentlichen Rundablage: ASP.NET MVC, Silverlight 2, WPF, WCF… | Code-Inside Blog

Post a Comment

Search Dev102