Skip past navigation, straight to the content

Category Archives: Work

Filipe Fortes used to work at Microsoft as a Program Manager on the Windows Presentation Foundation team — now he eats a lot of cheese.

Introducing Sistr

  • Plane Engine over the midwest

Over the weekend I spent some time seeing if I could replicate the functionality found in the excellent sIFR, using Silverlight instead of Flash. The result is Sistr. For the impatient — here’s a demo test page.

Note: This definitely isn’t ready for a production site, this is an early version for feedback purposes only. There are still plenty of bugs, trust me.

Usage

  1. Download sistr.js and save it to your web server (or reference it directly from this site).
  2. Create a zip file with the font(s) you wish to use. Upload this to your webserver as well (Silverlight will only use fonts that are retrieved via HTTP).
  3. Add the following into your HTML page:
    <script type="text/javascript" src="sistr.js"></script>
  4. In your CSS file, define a new class called sistr-replace (anything that starts with “sistr-” works). Here’s an example:
    .sistr-replace { }
  5. Use the font-family property to set the font name and URL to the font files, enclose them in quotes and separate with the “|” character (e.g. font-family: "Fil's Font|filfont.zip"). Make sure you also specify backup fonts for users who don’t have Silverlight installed, like so:
    .sistr-replace { font-family: "FontName|fonts.zip", Verdana, Arial, Sans-Serif; }
  6. Set the class property on some of your HTML elements to sistr-replace (or whatever else you used) and re-load. For example:
    <h3 class="entry-title sistr-replace">Hello World!</h3>
  7. Your text should now be rendered using Silverlight.

Take a look at the demo test page as well.

Pros & Cons vs. sIFR

Pro:

  • Simpler setup: All you need to do is include the sistr.js file in your page and edit your CSS — you do not need to edit any Silverlight or JavaScript code. sIFR is pretty easy too, but you need the Flash editing program in order to create a SWF file.
  • Support for Transparent Backgrounds: sIFR provides partial support, but it’s not recommended within Firefox (I believe this is an issue with Flash).

Con:

  • Lack of Silverlight Install Base: Silverlight is nowhere near as common as Flash.
  • No protection for Font Files: In order to use a custom font with Silverlight, you have to have the font file available for download on a web server — you cannot embed it or protect it in any way. This means you must use fonts that you either created or are liberally licensed (public domain, etc).
  • Immature: Both Flash and sIFR are much, much more mature than Silverlight and Sistr. There are many bugs that I have not sorted out yet.
  • Many limitations: See below

Known Issues

  • No support for line height: Limitation in Silverlight
  • Must use absolute units for font-size in IE: Due to IE’s lack of a getComputedStyle equivalent.
  • Occasional sizing issues: I think this may be a Silverlight bug, but occasionally text will get cut off in the vertical direction. Not sure how to fix it yet
  • Font size doesn’t respond to user changes: Works fine if you reload though
  • No support for :hover state
  • No support for nested hyperlinks
  • Text selection does not work: Not sure how screen readers react either
  • Cannot support nested bold in Firefox: Works in IE though

Let me know if you find others — or want to help fix bugs!

Adobe OnAir Seattle

Adobe AIR product roadmap

I went to Adobe’s OnAir Seattle yesterday, which was a really interesting event that I’d recommend attending if you have the time. Unfortunately, I had to leave before the end of the day, but here’s a summary of the notes I took while I was there.

The Big Picture

Adobe’s goal is to let web developers can use their existing skills (HTML, CSS, JavaScript, Flash, and Flex) to create desktop applications. AIR (formerly Apollo) provides cross-platform installation and application updates, a local database, and a variety of new APIs for managing local resources (local file access, controlling window chrome, drag and drop, etc). The Adobe guys were clear that this isn’t about porting existing web sites onto the desktop — assets and web services will obviously be re-used, but the emphasis was on not needing to learn new technologies (just a few new APIs).

Interesting Tidbits / Nerdy Technical Details

  • Installation: Applications are installed via a single .air file. Installed applications can be removed just like normal applications (i.e. via Add/Remove Programs on Windows, or by throwing the application in the trash on the Mac). An express install (which can bootstrap the AIR runtime) and detection is also possible via Flash.
  • Application Updates: AIR will provide support for automatic application update checking and upgrading.
  • HTML Rendering: Adobe chose the WebKit HTML engine (used by Safari and Konqueror) specifically because of it’s size and speed. Someone asked if they were considering moving to Firefox at some point, and they were clear that Firefox just couldn’t meet their size requirements for mobile.This cements WebKit’s position as the number three browser family (sorry Opera).
  • PDF Support: Requires Adobe Reader 8.1 — unlike HTML and Flash support, the Adobe Reader must be installed separately (I’m not sure what happens if it’s not installed).
  • HTML / Flash Integration: It looks like Adobe’s done a good job integrating the two — you can make script calls between the two, and there don’t appear to be any visual differences between the technologies. I’m not sure about PDF though, I’ll need to look into that.
  • Script Engine: They’re using the Tamarin JavaScript engine, which is far faster than what’s in browsers today. They showed a demo of BuzzWord, a word-processing program built on Flash, which implements their own line layout and pagination APIs that run pretty fast thanks to the JS engine. The Mozilla team plans to use Tamarin in Firefox version 4.0.
  • SQLite: This must be fairly new, because none of the talks or demos I saw were using the local database. Adobe did mention that they’re working with Google to make sure they’re API-compatible with Google Gears, which also uses SQLite.
  • Native Windows: Can create native windows, or go chrome-less windows with transparency that give full-freedom (at the potential cost of consistency with other applications on that OS).
  • Plugin Support: Currently only Flash and PDF can be embedded within HTML. Adobe says they’re open to feedback as far as other plugins (QuickTime was requested by a member of the audience).
  • SDK and Tools: Adobe already has mature tools with the Flash authoring environment, Flex builder, and Dreamweaver. They making sure to adding support for creating AIR packages (which are ZIP files) in their existing products, lowering the learning curve for developers. Command-line tools for packaging AIR files are provided as well.
  • Adoption Rates: Adobe made sure to mention how quickly new versions of Flash get adopted by users — they get 85% penetration within 9 months, which is quite impressive. Obviously, it’s unclear if AIR could get this
  • Linux Support: Planned in late 2008. Adobe says they’ve been waiting for the latest version of Flash for Linux before they port AIR.
  • Random Notes: Built-in support for associating file types at install time, don’t need admin rights to install AIR or AIR applications, events for regaining network connection, file dialogs, drag and drop support, use PNGs instead of dealing with .ico files, and Creative Commons licensing for the books.

MS vs. Adobe: My Take

This is the right strategic move for Adobe. They’ve managed to attack the biggest weaknesses of their chief competition, Microsoft’s WPF, by being cross-platform and leveraging existing technologies already used by web developers. Using existing technologies also means there are many mature tools for both designers and developers coding in HTML/Flash, which is not the case with WPF. Adobe made a good choice not trying to boil the ocean with a lot of new technology.

Granted, WPF’s target market is a bit different than AIR’s (there are a large number of WinForms developers already using .NET technologies), but for web developers the learning curve and lack of cross-platform support made WPF a non-starter (notice how much more interest Silverlight has recieved in the community). Obviously, there are still many areas where WPF is superior (3D and document layout, to name two), but I think AIR’s advantages more than make up for these drawbacks (from a web developer’s point of view).

Although still in it’s infancy, Silverlight will likely become the real competitor to AIR. Although it’s feature-poor in comparison to Flash, Microsoft’s clearly devoting a lot of resources to catching up quickly (notice the simultaneous release of 1.0 beta and 1.1 alpha — which surely required a lot of testing resources). Silverlight plays nicely with HTML and JavaScript, provides good language support (including trendy languages like Ruby and Python), and has a very fast script runtime as well. It already lets you go into full-screen, I don’t think adding more windowing APIs wouldn’t be a stretch. I fully expect Microsoft to move in this direction.

Obvious Disclaimer: I do not work for Microsoft (although I used to). I don’t have any inside information. Don’t take blog posts too seriously, especially ones typed hurriedly on a hot day.

Font Rendering Across Rich Platforms

Although I used to work for Microsoft on the WPF team, I’m not tied to the platform. WPF and its alternatives (Flash, HTML, Apollo, Silverlight) each have advantages and disadvantages and choosing between them depends on your requirements. Since I’m doing a lot of work around reading experiences, I thought it was a good time to go back and re-evaluate the existing choices.

In this post, we’ll look at how each platform renders fonts at 9, 10, 12, and 14 points — sizes commonly used for reading. I’ve used three fonts:

  • Verdana: The old standby, installed on many systems.
  • ITC Cheltenham: A serif frequently used in newspapers.
  • Gotham Rounded: A sans-serif that I happen to like.

For no good reason, I’ve placed the results in alphabetical order. First up is Flash.

Flash

Up until a few years ago, Flash used to render fonts poorly at small sizes. Most authors worked around this limitation by changing the type of anti-aliasing used when displaying fonts. Flash provides two anti-aliasing options, one for readability and the other for animation. Additionally, Flash also allows the author to disable anti-aliasing altogether, and use aliased bitmap fonts. Flash 8 introduced a new rendering engine that vastly improved the quality of small-type text.

At small sizes, the readability setting is (unsurprisingly) far superior to the animation setting. Here’s a sample of the readability anti-aliasing for Verdana at 10 point:

10pt Verdana in Flash readability setting

For the same font and size, the animation setting is quite ugly:

10pt Verdana in Flash animation setting

Although it creates clearly more readable results, the readability smoothing creates a strange coloring affect that can be pretty noticeable at small sizes. Here’s Gotham Rounded at 9pt:

9pt Gotham Rounded in Flash readability setting

On my monitor, the effect is subtle, but noticeable — I see a bit of color around the edges of the letters.

Flex / Apollo

Apollo (through Flex) has two different font rendering engines — one of which seems to be shared with Flash (the documentation is a little vague here, so feel free to correct me if I’m wrong). The other rendering engine has access to installed fonts, and is recommended for small type sizes — however the quality is quite bad. From my simple tests, it seems that the fonts are always aliased, producing the jaggy look seen below:

10pt Verdana in Flex

This aliased look is acceptable for some fonts, such as Verdana, that have reasonable bitmap representations at small sizes. However, for many fonts the result is unacceptable, such as this sample of Cheltenham at 10 point (from Flash set to bitmap, not Flex):

10pt Cheltenham, Bitmap mode in Flash

Except for extreme cases, it looks like it’s best to use the Flash font rendering system when writing an Apollo (or Flex) application. (Once again, I’m under-educated in the Apollo and Flex realms, feel free to drop some knowledge in the comments)

HTML

On my machine, the Firefox and Internet Explorer 6 both rendered extremely similar results. The Firefox rendering is shown below:

10pt Cheltenham in Firefox

The lack of subpixel positioning destroys the serif font at small sizes. You can see the effect at larger sizes as well — here is Cheltenham at 14 point:

14pt Cheltenham in Firefox

You can see the strange letter spacing in the first line — compare “Marketing” and “cross” to see the difference.

The sans-serif fonts fared better in the browser, with Verdana doing particularly well as it was specifically tuned for on-screen use.

Internet Explorer 7 uses ClearType for its font rendering, and should therefore produce results that are nearly identical to WPF.

Silverlight

Silverlight is the least mature of the platforms (since Apollo leverages both Flex and Flash). The 1.1 Alpha version that I tested unfortunately does not support for the Adobe CFF font format — meaning I was unable to test Cheltenham or Gotham Rounded. Silverlight doesn’t use the ClearType algorithm used by WPF, instead it uses gray scale anti-aliasing with gamma correction. The results are generally good, with the clear weakness being at small sizes. Here is Verdana at 9pt in Silverlight:

9pt Verdana in Silverlight

At this small size, Verdana looks a bit fuzzy. The effect is less noticeable at 10 point, but still there.

WPF

All text in WPF is rendered with ClearType — developers have no way of opting out of this (actually, there is a way, but it’s pretty awkward and not really well known). The quality of text at small sizes is impressive, here’s Gotham Rounded at 9pt in WPF:

10pt Cheltenham, Bitmap mode in Flash

It’s slightly fuzzy and a bit gray, but overall a bit better than the flash version.

Verdict

Overall, the results are pretty good. The only engine with poor results is the native Flex engine, but with support for Flash, there’s a clear, easy to use alternative at your disposal.

Although the browsers work quite well with standard web fonts (and any other specifically tuned for small sizes), they are not an acceptable choice for traditional print fonts — especially Serif faces (Internet Explorer 7 being the exception). Considering the lack of cross-browser font-embedding, this probably isn’t a problem for most.

Silverlight is still a baby in this space, and it shows (there’s currently no way to set line height, for example). The anti-aliasing looks pretty good at larger sizes, but is noticeably fuzzy at smaller sizes. Although it’s better than what most browsers provide, it still has a way to go before catching up to Flash and WPF.

The final two contenders are Flash and WPF — and it’s a close call when it comes to rendering. Here are three side-by-side samples for WPF and Flash. The first is Verdana at 9 point (all samples show Flash with readability anti-aliasing):

WPF vs. Flash for Verdana 9 point

Although the Flash version has a nicer color, the WPF wins by a hair here, for being a bit smoother and less blurry (look at the “B” in “Branding” in the Flash version, third line from the bottom). Let’s move on to Gotham Rounded at 9pt:

WPF vs. Flash for Gotham Rounded 9 point

Once again, Flash has stronger lines that WPF, but it’s uneven and has a bit of color fringing. Finally, let’s look at Cheltenham at 12 point:

WPF vs. Flash for Cheltenham 12 point

This time, WPF is a bit darker than Flash. This one is really a toss-up and depends on personal preference. Flash is a bit sharper, but the WPF version is smoother and more consistent.

Overall, I think WPF has the edge when it comes to font rendering, although it’s quite close and could easily come down to user preference.

Next Steps

This analysis is a bit rough, there’s a bunch on my to-do list here, including:

  • Testing FlashType in Flex and Apollo
  • Testing non-CFF fonts in Silverlight
  • IE 7, Mac OS, and Ubuntu screenshots
  • More fonts

Also, the font rendering is just one aspect of a user’s reading experience. Obviously layout, performance, installation, and many other factors come in to play here. Subscribe to feed to make sure you don’t miss the next installments.

Raw Results

If you’re interested, here are the screenshots from each test application, in PNG format: fontrendering.zip (Zip, 500K)

The Sad State of Online Advertising

While reading an article in today’s New York Times, I saw the following sleazy ad:

Paris Hilton Ad in NYTimes

How tall is Paris?

Answer correctly to receive your Pink Laptop

You’ve probably seen this genre of ad before, which offers free merchandise for a trivial task — of course, the ads always state that “Details Apply” in tiny text (I wonder how the FTC feels about these “details”).

As stupid as these ads are, they’re not much worse than the advertisements for escort services that you see in back pages of a free weeky — but you’d never see one of those next to a top story in the print edition of the New York Times!

Why not? Money, of course. A prominent ad in the print edition of the NYT is far too expensive to be purchased by the low-class advertisers — and even if it were cheap enough, the NYT’s higher-end advertisers (luxury companies such as Tiffany’s, who spend a lot of money to consistently advertise in the paper) would never allow their brand to be anywhere near an ad like that.

But it turns out that Tiffany’s and other high-end advertisers don’t advertise on the web — because there’s no appropriate online advertising surface out there for them. This missing business causes two side-effects:

  1. The scummy advertisers aren’t priced out of the market
  2. The Times, faced with low-revenues in their online edition, can’t be as choosy when it comes to advertisers

Broader Markets are Good

One could mis-interpret my previous statements and say that I’m an advertiser snob, looking to price out the little guy. This, of course, is false. Even with way less than ten percent of the advertising market, the Internet has brought more advertisers into the market — this is undoubtedly a good thing.

Large publishers, like the Times, can (and should) still cater to the little guy. Unlike the print version, an online edition need not display the same advertisement for all readers in perpetuity. A digital publication can sell limited run, or niche-targeted advertisements at a lower total cost and higher visibility than they could in the one-size-fits-all print edition. In fact, I’m certain they already do so.

Publishers like the Times have to start being picky and demanding a certain level of quality from their advertisers. In the print world, it’s clear that advertisements are part of the content (look at any fashion magazine if you’re in doubt) — this attitude needs to extend to the digital realm.

Moving toward a better future

At Mix, I showed some sketches of what online Magazines can become. Roger Black and I are working to create higher-end content experiences that won’t dilute the brand of luxury advertisers. Rest assured, you won’t be asked to punch a monkey.

It’s still early, so all I have to show are sketches — but there’s a lot of room for improvement in this space! I’m a bit surprised by the state we’re in today, because so many of today’s mistakes come from ignoring the lessons learned during decades of print publishing. Of course, digital is a different medium than print, which means that we need new plenty of new paradigms in order to succeed — but that just makes it all the more exciting!

Update: Other Voices

After writing this post, I found P.J. Onori’s excellent (and similarly-titled) article The Sorry State of Online Advertising — which I recommend. He makes similar points (and posted them first, so he wins):

I would argue that the sheer number of advertisements some of these sites have on their site is evidence that the current ad model is not working. Instead of thinking of more original, symbiotic and user-friendly forms of advertising, most site creators have subscribed to the “more ads means more revenue” philosophy. This current relationship between the site creator and advertisers is much like a building landlord and a renter. Space is offered to the advertiser and other than the exchange of money, there is little to no relationship between the two. Under this model, the landlord attempts to rent out all the space to whoever offers money. The problem with this model is that if the landlord just rents out rooms to anyone without any discernment, the landlord’s property could be quickly destroyed by the renters. Meanwhile, the apartment building is in shambles and no one is interested to look at the space, much less rent it. Similarly, if a website does not carefully choose its advertisers, the web site could shortly be a ghost town. An interest in short-term gains can ultimately disenfranchise a site’s users to the point that they do not come back. Guess what, advertisers are going to drop you like a bad habit once you are not giving them what they want - click-throughs and revenue.

Another article worth reading is The Devil & Online Advertising by Darius A Monsef IV. Here’s an excerpt:

Do you know why you only see those terrible, low-budget ads on your local television stations? Because it costs too much for those guys to hock their “Super-Mega-One-Day-Only-Sales-Extravaganza!” on national television. When the price point to advertise online is in the pennies per CPM, then you’re going to end up with low-quality advertisers.

UniformPanel

A few months ago, Nick Thuesen posted his SpanningStackPanel class, which is basically a cross beween UniformGrid and StackPanel. Around that time, I was working on a project that called for exactly that layout.

Unfortunately, Nick’s panel didn’t work in my application because he was modifying the Children collection in his code, which is a big no-no if you want to support databinding (e.g. in order to use it as the ItemsPanel within a ListBox). I ended up writing my own version, adding a few features that were required for the project.

At Mix, I promised Nick I’d post and get him the fixed source code. You can download the source (plus some basic tests) in the first version of the Fortes Panel Pack (currently “Pack” is a misnomer, since there’s only one — but I have a few more waiting to be packaged for external consumption).

Features / Release Notes:

  • All the features of Nick’s original
  • Support for data-bound children
  • Special support for Expander children: Detects collapsed Expander elements and treats them as fixed-size elements
  • Bug: Support for Expander within a Template does not lay out correctly on the first pass — see the DataBoundPanels.xaml file in the sample project. Resizing the window, or any other action that causes a relayout, fixes the issue. (I’ll fix it in the next release)

Video and Screenshots from the Mix Panel

Microsoft has posted videos from the Mix sessions, which means you can view the video of our panel online. There’s also a WMV version you can download directly (roughly 80 MB).

Unfortunately, the production quality of the video isn’t very good. The video shows only the projection feed, which was fairly static except for about 25 minutes worth of demos by myself and Tom Bodkin. Also, the projector in the room was running at 1280 by 720 pixels, which was then (stupidly) stretched to a different aspect ratio for the video. I’ve included a few non-stretched screenshots from my demo below:

Indigo Demo - Front Page

Indigo Demo - Geico Ad

Indigo Demo - Most Popular

If you don’t feel like watching the video, Tim Anderson has written a good summary of the panel.

During the session, I showed a demo that myself and Roger Black (amongst others) have been working on in the past couple of weeks. It’s a rendition of the English-language version of Reporte Indigo, a Mexican online weekly magazine currently done in Flash. Our goal was to show some of the directions we see online reading experiences moving toward: richer, branded layouts that look good across a variety of screen dimensions, integrated media, richer advertisements, and continued increases in community-driven features. My big fat mouth has more to say about this area, but that will have to wait until another post.

Come See Me at Mix

Those attending Mix 07 next week in Las Vegas might be interested in going to Beyond the Reader: Improving the Online Media Experience, a panel discussion featuring yours truly (along with Roger Black of The Font Bureau/Danilo Black and Tom Bodkin of the New York Times). It’s currently scheduled during the first timeslot on Wednesday morning.

Here’s the abstract:

Is it really possible to make online narrative content glamorous? Smart designers are complementing their traditional strengths in branding and narrative with technologies such as WPF to create highly flexible, readable and vibrant online media products. See how designer-delivered digital media can work on-and-off-line, in-and-outside the browser. Envision next year’s portal digital world and how can you become part of it. For producers of newspapers, magazines, and TV content, this is the next Web.

Block Elements

Unlike Inline elements, Block elements take up the entire width of the text column and have line breaks before and after their content. By far, the most common block element is Paragraph.

Here are the elements that shipped with WPF that derive from Block:

  • Paragraph: With a straightforward name, this element (along with TextBlock) is the only container for Inline elements.
  • Section: A container for other Block elements — analogous to Span, which contains Inline elements.
  • BlockUIContainer: A container for UIElement-derived classes to be displayed as a block. Analogous to InlineUIElement.
  • List: Creates an ordered or unordered list. Contains ListItem elements.
  • Table: Contains TableRowGroup
  • elements.

Additionally, there are a few helper classes that are a bit block-ish:

  • ListItem: Block container for use within a List.
  • TableRowGroup: Container for TableRow objects.
  • TableRow: Container for TableCell objects.
  • TableCell: Block container for use within a TableRow.

Just like the inline elements, all of these elements do not derive from UIElement or Visual — this is because they do not have a one-to-one mapping between their content and visuals on screen. The reasons for this, and their ramifications, will have to wait for the next post.

Differences from HTML

  • No nested paragraphs: It’s worth re-iterating, because you’ll probably run into it some time.
  • Strict structure for Lists and Tables: WPF is strict about the structure of Lists and, in particular, Tables. This leads to verbose markup.
  • Only one List: Unlike HTML, there are no specialized elements for ordered and unordered list. You use the MarkerStyle property.

Inline Properties

Now that we’re roughly familiar with the inline elements, let’s look at the formatting properties each of them expose.

Properties from TextElement

TextElement is the superclass for all classes used for text (with the exception of TextBlock). TextElement defines formatting properties that can be applied universally to text.

FontFamily

Controls what is commonly known as the “font” of the text. Like CSS, you can give a comma-separated list of alternatives such as FontFamily="Calibri, Verdana, Helvetica, Arial". Note that, unlike CSS, you cannot use generic names such as Serif, Sans-Serif, and Monospace. Like CSS, there are a few generic names you can use: Global Monospace, Global Serif, Global Sans Serif, and Global User Interface.

FontSize

The size of the font in “WPF pixels” (1/96 of an inch). Note that this is not equal to the traditional font size measure of points (1/72 or 1/72.27 of an inch depending on how precise you want to be). As with other measures, you can use shorthand in markup to get sizes in points, inches, etc (e.g. FontSize="12pt" or FontSize="2cm").

Foreground

The color of the text. This property is actually a Brush, which means you can do cool things like draw text with a gradient.

FontWeight

Controls the darkness of the font face — typically used to make text bold. This is a value between 1 and 999, or one of the following value shortcuts: Thin, ExtraLight, Light, Normal, Medium, SemiBold, Bold, ExtraBold, Black, ExtraBlack. Most fonts only have two weights (Normal and Bold) — but the nice ones that designers like have many more. If the font doesn’t have the weight you request, WPF will choose the weight closest to the value you specified.

FontStyle

Used to italicize text. There are three values: Normal, Italic, and Oblique. Almost every font defines special characters for the Italic style, while Oblique draws the same characters as Normal, but on a slant (inevitably looking worse, and being less readable, than the italic face). The difference is illustrated below:

Examples of Italic, Oblique, and Normal-styled text

FontStretch

If a font has multiple faces with different widths, this allows you to choose between them. Valid values are between 1 and 9, but like FontWeight, there are named shortcuts: UltraCondensed, ExtraCondensed, Condensed, SemiCondensed, Normal, SemiExpanded, Expanded, ExtraExpanded, UltraExpanded. Unfortunately, only high-end fonts come with these faces (WPF will not algorithmically stretch a font).

TextEffects

Used to apply an effect to a piece of text. See my previous post on TextEffects for a thorough description.

Typography

This property is very large, and merits (several) posts of it’s own. Basically, this property exposes the many of the advanced features available from OpenType fonts (aka, expensive fonts you probably don’t have but wish you did).

Here’s a list of the various options available through the property (I’ve already posted examples for some of these properties, I’ll add links as I write more samples — Warning: the XAML in those older posts is probably no longer valid due to namespace changes and property renames):

  • AnnotationAlternates
  • Capitals: Small caps, etc
  • CapitalSpacing
  • CaseSensitiveForms
  • ContextualAlternates
  • ContextualLigatures
  • ContextualSwashes
  • DiscretionaryLigatures
  • EastAsianExpertForms
  • EastAsianLanguage
  • EastAsianWidths
  • Fraction
  • HistoricalForms
  • HistoricalLigatures
  • Kerning
  • MathematicalGreek
  • NumeralAlignment
  • NumeralStyle
  • SlashedZero
  • StandardLigatures
  • StandardSwashes
  • StylisticAlternates
  • StylisticSet1 through StylisticSet20: Yes, there are really twenty of them.
  • Variants: Used for Subscript, Superscript, etc

Phew, that was a long list! Lucky for you, there won’t be a test any time soon. Moving on …

Properties from Inline

The Inline superclass defines three new properties that can be applied on inline text.

TextDecorations

This property lets you draw a horizontal line around the text — it’s mostly used to underline a word. There are four possible line positions: Underline, Overline, Strikethrough, and Baseline. Underline draws a bit below the baseline so the line doesn’t touch the (most of) the actual letters, while Baseline is drawn directly on the text baseline.

You may have noticed that the name of this property is plural, that’s because you can set more than one decoration for the text. Unfortunately, the syntax for this isn’t as clean as TextDecorations="Underline Overline", you have to use much more verbose syntax:

<Run>
  <Run.TextDecorations>
    <TextDecoration Location="Underline" />
    <TextDecoration Location="Overline" />
  </Run.TextDecorations>
  Help! I'm surrounded by lines
</Run>

Also, an individual TextDecoration has a Pen property, meaning you can choose the Brush used to draw the line, change the Thickness, or each use the DashStyle property to change how your underlines work (it will surely look awesome on your MySpace).

BaselineAlignment

This property allows you to vertically position an inline element within the line. The legal values are: Bottom, Baseline, Center, Top, Subscript, Superscript, TextBottom, and TextTop. The image shows the values in action:

Illustration of the values of the BaselineAlignment property

There are some fine typographic distinctions between TextTop, Top, and Superscript (as well as their mirror values for the bottom) — but I’m guessing you don’t really care about those (they’re pretty much the same as CSS, if you really must know).

You probably won’t use this property very much, but it comes in handy when you’re dealing with non-text objects (i.e. things within an InlineUIContainer), or if you’re trying to create a fake subscript or superscript effect because your font doesn’t support the real thing.

FlowDirection

This property is useful if you’re including text from languages that use a right-to-left reading order (such as Arabic or Hebrew). It’s also exposed on many other elements, such as FlowDocument and all the Block-derived classes.

“Content” properties of inlines

Except for LineBreak, each Inline exposes a property that allows you to set it’s content. Unlike Control.Content, which is of type object, each of these properties is strongly-typed to the kind of content it can contain:

  • Run.Text of type string
  • Span.Inlines of type InlineCollection
  • InlineUIContainer.Child of type UIElement

Additionally, Hyperlink exposes a few properties (such as NavigateUri) so you can actually make a link functional.

Once again, we’ll skip over Figure and Floater for now — we don’t have enough background for them yet.

Differences from HTML

With the exception of TextEffects and Typography, these properties are quite similar to their CSS counterparts. You’ll run into slight spelling annoyances (CSS uses dashes in their names and values, while WPF does not, href is much easier to type than NavigateUri) — but you should feel pretty comfortable.

The exceptions would be the properties that don’t have CSS analogues: TextEffects and Typography. However, these properties aren’t used very frequently, so you rarely need to mess with the defaults.

Inline Elements

The term inline may be familiar if you know HTML and CSS — an inline element is displayed within an existing flow of text, positioned on lines of text shared with other inline elements.

Let’s make this more clear with a screenshot and a bit of code:

<Border xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" HorizontalAlignment="Center" VerticalAlignment="Center" BorderThickness="1" BorderBrush="#ccc" Padding="10">
  <TextBlock TextAlignment="Left" TextWrapping="Wrap" Width="400" FontSize="25" FontFamily="Candara">
    <Bold>Of Montreal:</Bold>
    <Hyperlink Background="#cef">Hissing Fauna, Are You The Destroyer?</Hyperlink>
    <Italic>(2007)</Italic>
  </TextBlock>
</Border>

The text 'Of Montreal: Hissing Fauna, Are You The Destroyer? (2007)'

In our example, we are using three inline elements: Bold, Hyperlink, and Italic. Each of these shares space on a line within our TextBlock (you can think of it as a paragraph). I added a background to the Hyperlink element to emphasize the fact that the element is broken across a line.

Here are all the elements shipped with WPF that derive from Inline (you can, of course, subclass and add your own):

  • Run: A string of text.
  • Span: A container for grouping other Inline elements. Its subclasses provide default formatting, and linking:
    • Bold
    • Italic
    • Underline
    • Hyperlink
  • LineBreak: Forces a hard line break within a text flow. Provided as a markup convenience (newline characters are honored if used within code).
  • InlineUIContainer: A container for UIElement-derived classes within text.
  • AnchoredBlock: I’ll cover these in detail later, but note that these cannot be used within a TextBlock
    • Floater
    • Figure

As I’ve mentioned before, it’s rarely necessary to explicitly use Run when writing markup (although it’s important when writing code). The same mechanism is used with InlineUIContainer for convenience.

Span and its subclasses are straightforward for those with experience with HTML, as is LineBreak.

Figure and Floater don’t have direct analogues in HTML, but the functionality is similar to the CSS property float. More on these later.

Differences from HTML

If you’re already familiar with HTML/CSS, then the concepts in this entry are old news to you. For easy skim-reading, here are the major differences between WPF XAML markup and HTML markup for inline elements:

  • No semantic classes: This is a subtle, but important, point — the markup classes exposed in WPF have no semantics, they are presentational only.
  • Once an Inline, always an Inline: This is partially a consequence of the previous point, but unlike CSS, you cannot change the display-type of an element — i.e. you can’t change an element from inline to block, or vice-versa. If you want to do that, you must change the elements used and the tree structure.
  • Can’t nest paragraphs: The content model is strict, so you can’t directly put a block element within a Paragraph (we’ll learn how to do this via InlineUIContainer or an AnchoredBlock in later posts).
  • Invisible container elements: Run and InlineUIContainer may not be in the markup, but they’re there if you walk the tree.

Next, we’ll look at the properties you can apply to inline elements.

Creating WPF Text Layouts is Hard

I’ve heard many people ask for advice on creating attractive text layouts using WPF — with good reason! There are quite a few challenges, in my opinion, the top difficulties are:

  1. Differences from HTML/CSS: More than any other part of WPF, the System.Windows.Documents namespace has many similarities with HTML/CSS — but the differences are significant enough to cause real issues.
  2. Lack of good examples: The technology is still new, so there aren’t many role-models out there to learn from. The lack of view-source capability makes it tough to steal learn from others.
  3. Variable-column layout is hard: Without a doubt, designing a document that looks good when reflowed into a variable-number of columns is difficult.
  4. Lack of a designer: This is a tough one.

It’s a bit ambitious, but I’m going to do what I can to help fix these problems.

Obviously, this will take many entries — let me know if I’m missing anything, or if you have specific questions you’d like me to address.

BindableRun

A useful feature that was left out of the first version of WPF is the ability to databind the value of Run.Text. I was still around when this feature was (unfortunately) cut — but don’t despair! It’s not actually that hard to write yourself.

We’ll do this by creating a subclass of Run, which I’ve creatively named BindableRun.

using System;
using System.Windows;
using System.Windows.Documents;
 
namespace BindableText
{
  /// <summary>
  /// A subclass of the Run element that exposes a DependencyProperty property 
  /// to allow data binding.
  /// </summary>
  public class BindableRun : Run
  {
    public static readonly DependencyProperty BoundTextProperty = DependencyProperty.Register("BoundText", typeof(string), typeof(BindableRun), new PropertyMetadata(new PropertyChangedCallback(BindableRun.onBoundTextChanged)));
 
    private static void onBoundTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      ((Run) d).Text = (string) e.NewValue;
    }
 
    public String BoundText
 
      get { return (string)GetValue(BoundTextProperty); }
      set { SetValue(BoundTextProperty, value); }
    }
  }
}

The code is pretty straightforward, we create a new DependencyProperty in the usual manner. Then we add a PropertyChangedCallback that manually sets the Text property. That’s it! We rely on the base class to take care of everything else.

You can use this in DLL, by declaring an XML namespace and linking it to a CLR namespace, as in the example below:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:bt="clr-namespace:BindableText;assembly=BindableText">
  <FlowDocumentScrollViewer>
    <FlowDocument>
      <Paragraph>
        You can control the value of this text through the TextBox below: <bt:BindableRun FontWeight="Bold" BoundText="{Binding ElementName=tb, Path=Text}" />
      </Paragraph>
      <BlockUIContainer>
        <TextBox Name="tb" Text="This is text with spaces that wraps across a line … like this!"/>
      </BlockUIContainer>
    </FlowDocument>
  </FlowDocumentScrollViewer>
</Page>

If you’re running this in XamlPad, you’ll have to make sure that the BindableRun.dll file is in the same directory as XamlPad itself. You can do this by either creating a new copy of XamlPad.exe or copying the BindableRun.dll into the directory where you keep XamlPad (C:\Program Files\Microsoft SDKs\Windows\v6.0\Bin in my case).

If you want to download this class, I’ve created a project (with the DLL) that you can download and use: BindableText.zip (13 KB).

Update 3/21: Paul Stovell mentions an alternate technique that creates an attached property instead of a subclass to achieve the same effect.