Welcome to MSDN Blogs Sign in | Join | Help

IgnoreWhitespace: a Custom Attached Property for WPF

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:

  1. Add the Text.cs file to your WPF project
  2. Add the xmlns:synergist=clr-namespace:Synergist” to root element of your XAML file
  3. 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.

Published Friday, January 30, 2009 5:43 PM by Michael S. Scherotter

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Anith &raquo; IgnoreWhitespace: a Custom Attached Property for WPF

# Silverlight Cream for January 30, 2009 -- #502

In this issue: Fredrik Normén, Michael S. Scherotter(2), Gerard Leblanc, Lee, and Jesse Liberty. Shoutouts

Saturday, January 31, 2009 2:34 AM by Community Blogs

Leave a Comment

(required) 
required 
(required) 

  
Enter Code Here: Required
 
Page view tracker