Home > Microsoft .Net Development Tips > .NET Developer > How to list fonts in WPF using markup extensions and data templates
Win Development Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

.NET DEVELOPER

How to list fonts in WPF using markup extensions and data templates


Walt Ritscher, Contributor
05.06.2009
Rating: --- (out of 5)


.NET Essentials Channel
Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google


Dig through the .NET class libraries for a few minutes and you'll find collections (islands) of static data. For example, the Fonts class exposes two static properties, Fonts.SystemFontFamilies and Fonts.SystemTypefaces, which are useful for enumerating the installed fonts on the system. In this tip, I'll show you how to list font families in WPF by filling a ListBox with the FontFamilies data.

Binding to Static Data

WPF has a special markup extension for retrieving static data. Markup extensions are classes that are called by WPF at runtime to provide a way to access static properties. Any public static field or property can be used via the x:Static markup extension. For instance, the following code snippet shows a class with a static property:

class Document {
  // defines a static property or field
  public static double DocumentWidth { get; set; }
}

The XAML snippet to retrieve the static DocumentWidth property would be:

<Grid>
  <!-- assumes you have a xmlns:local declaration pointing to the 
      assembly containing the Document class -->
  <RichTextBox Width='{x:Static local:Document.DocumentWidth}' />
</Grid>

Binding to FontsFamily property

Now that you understand the x:Static markup extension, let's see how to bind a ListBox to a static collection.

<!-- DataContext specifies the binding source 
     for any bindable property in the ListBox or its children.
     ItemsSource specifies the source of list data
     In this example the ItemsSource is bound to the DataContext data
     -->
 <ListBox DataContext="{x:Static Fonts.SystemFontFamilies}"
  ItemsSource='{Binding}'
  HorizontalContentAlignment='Stretch'>

 </ListBox>
ListBox showing plain fonts

As you can see from the screen shot, the ListBox is filled with the font data. This font list is serviceable, but it's also boring. You've probably seen font lists in other applications that preview the font by as showing the font name in the actual font. Data templates are the key to creating this type of UI in bound lists.

Data Templates

A data template is an alternate UI for your application data. When WPF attempts to render your data, it checks to see if there is a template available. If so, the template is expanded and applied to your data prior to rendering to the screen. In the next example, a data template is assigned to the ListBox ItemTemplate. Note that while this template is declared within the ListBox element, it could also be placed in the Window.Resources section.

<ListBox.ItemTemplate>
        <!-- Apply a template to each Item in listbox -->
    <DataTemplate>
    <!-- DataTemplate is affliated with the bound data.    
    in this case the FontFamiles property-->
    <Border Padding="5"
        Margin='0,5'
        BorderBrush='LightBlue'
        CornerRadius='4'
        BorderThickness='4'>
    <StackPanel Orientation='Vertical'>
    <TextBlock VerticalAlignment='Center'>
    <!-- ContentPresenter is the placeholder in the template
    where the bound data should be rendered. 
    In this case, I'm placing it within
    this TextBlock -->
    <ContentPresenter Content="{TemplateBinding Content}" />
 
    </TextBlock>
    <!-- use the bound data to set the FontFamily
    for this TextBlock -->
    <TextBlock FontFamily='{Binding Source}'
        VerticalAlignment='Center'
        Margin='20,3'
        Foreground='DarkGray'>ABC DEF GHI JKL MNO PQR STU VWYZ
    </TextBlock>
    </StackPanel>
    </Border>
    </DataTemplate>
 
    </ListBox.ItemTemplate>

</ListBox>

The ListBox should now look like this:

ListBox showing WYSIWYG fonts

Walt has trained thousands of corporate developers during the last 14 years and he travels the world speaking at software conferences, and providing developer training for corporations. He writes for several IT magazines, and worked on books/videos and .NET courses for Microsoft Press. As a Wintellect consultant he is presently focused on the WPF, Surface and Silverlight APIs. Walt is also a Microsoft MVP, WPF Disciple, Silverlight Insider and author of the free Shazzam WPF Shader utility.

Rate this Tip
To rate tips, you must be a member of SearchWinDevelopment.com.
Register now to start rating these tips. Log in if you are already a member.


Submit a Tip




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us    Add to Google



RELATED CONTENT
.NET Developer
How to speed up Visual Studio 2008's slow WPF designer
How to convince management to buy Microsoft Visual Studio 2008
Microsoft webcast series previews new Visual Studio 2010 features
New features in Windows 7 bring new UI considerations for developers
User Account Control (UAC): How to develop code for standard users
Introduction to Vista's user account control (UAC) for developers
Visual Studio 2008 code metrics tools will help keep code clean
Downloadable MSDN library released for VS 2008 SP 1
Widgetbox provides good example of how to use Facebook Developer Toolkit
Microsoft previews new features in Visual Studio 2010

.NET Framework 3.5 and Visual Studio 2008 development
Microsoft's message at TechEd: make the most of what you have
How to speed up Visual Studio 2008's slow WPF designer
How to convince management to buy Microsoft Visual Studio 2008
Moonlight 1.0 release brings Silverlight to Linux
Microsoft cuts Visual Studio 2008 upgrade prices as VS 2010 looms
User Account Control (UAC): How to develop code for standard users
How to write installers in Vista that work correctly under UAC
How to elevate programs' privileges correctly using Vista's UAC
Introduction to Vista's user account control (UAC) for developers
Microsoft offers startups free development tools, MSDN subscription

Windows Presentation Foundation
How to develop applications targeting both Silverlight and WPF
How to speed up Visual Studio 2008's slow WPF designer
Fast guide: Silverlight blogs
Modeling tool provides 3D components for WPF apps
VantagePoint WPF Controls delivers rich suite of UI components
Mobiform releases WPF component set
ComponentOne adds rich-text editor to Studio Enterprise
Windows Developments: Product news, December 2007
Book Excerpt: What's new in Windows Presentation Foundation
What Visual Studio 2008 brings to client application development
Windows Presentation Foundation Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
Cosmos  (SearchWinDevelopment.com)
IronRuby  (SearchWinDevelopment.com)
Visual Studio Express (VSE)  (SearchWinDevelopment.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



Database Programming Solutions - .NET XML, Visual Studio LINQ, ORM .NET
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides technology professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective purchase decisions and managing their organizations' technology projects - with its network of technology-specific websites, events and online magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2000 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts