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.



Tags :

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

  1. contrapunctus

    Said on May 4, 2008 :

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

  2. 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

  3. Galaxia

    Said on February 13, 2009 :

    I dont think you can do this in the latest silverlight with v3.5.
    unless you have a more complete code sample.

  4. Galaxia

    Said on February 13, 2009 :

    I get a static not supported error using the below code.

  5. Galaxia

    Said on February 13, 2009 :

    we cant post code?…what a fab code forum…lol

2 Trackback(s)

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

Post a Comment