In the blog post I just wrote, I found a peculiarity of XAML (both WPF and Silverlight) where nicely looking XAML would sometimes cause unexpected behavior. I sent an email to the WPF team asking them to add an IgnoreWhitespace property to the Paragraph and TextBlock elements. Since I’m the Synergist and not Scott Guthrie, I don’t expect that feature to be in the next version of WPF and Silverlight. Oh well.
But I could add it myself. The very smart people on the WPF team created this concept of Custom Attached Properties where anyone can write their own property to be added to any DependencyObject in WPF or Silverlight. I took about a half hour to write an IgnoreWhitespace property that would allow me to write my XAML like this:
<FlowDocument xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:synergist="clr-namespace:Synergist"> <Paragraph synergist:Text.IgnoreWhiteSpace="true"> <Run Text="gym"/> <Run Text="nasium"/> <LineBreak/> <Run Text="Hello"/> </Paragraph> </FlowDocument>
I've uploaded the code for the custom attached property to the MSDN Code Gallery. To use it, do the following:
- Add the Text.cs file to your WPF project
- Add the xmlns:synergist=clr-namespace:Synergist” to root element of your XAML file
- Add the synergist:Text.IgnoreWhitespace=”true” attribute to any TextBlock or Paragraph element that uses Runs.
I’ve also uploaded a Silverlight 2 version that is almost identical (the DependencyProperty:RegisterAttached method is slightly different and Paragraph isn’t in Silverlight). You use it in exactly the same way.