Skip past navigation, straight to the content

Collapsed Spaces Around <Run />

In response to my previous post, Nick asks:

Why are my spacings dropped when I have: <Run>NYC </Run> <Run> Hickster</Run>? This comes out NYCHickster

The space collapsing around Run can be a little tricky. The easiest thing to do if you’re running into this issue is to use Run.Text, like so:

<Run Text="NYC " /><Run Text="Hickster" />

This technique works for inserting multiple spaces as well.

Update 3/18: Sheva points out a different method I had completely forgotten about — using xml:space="preserve":

<Span xml:space="preserve"><Run>NYC</Run> <Run>Hickster</Run></Span>

6 Comments

  1. I’m sure there is probably a very good reason, but why would WPF not recognize spaces between tags? Seems to ignore the idea that spaces are characters too. Are you an anti-spacite?

    Posted Mar 15, 2007 at 6:59pm | Permalink
  2. Mike — Did you ask this question just so you could use that joke?

    The WPF parser is quirky when it comes to collapsing spaces around tags, and honestly, I don’t know all the rules (been a long time since I worked there, I guess).

    Posted Mar 16, 2007 at 6:33am | Permalink
  3. Actually you can preserve the white spaces between element tag using the following trick:

    Sheva

    Posted Mar 18, 2007 at 1:14am | Permalink
  4. fil – well, yeah… partially.

    It’s always bothered me that 1 or more spaces/tabs in HTML only ever get translated to 1 space. I realize that it’s probably to prevent stupid users from creating whitespace-based layouts, and also to allow the source to be formatted to be easily read without affecting the rendered page. But doing so seems to create confusion and also rounds the edges off of what should be a more strict document interpretation.

    Posted Mar 19, 2007 at 9:00am | Permalink
  5. Fil-
    I can’t repro. See: http://rrelyea.spaces.live.com/blog/cns!167AD7A5AB58D5FE!1781.entry
    Thx, Rob

    Posted Mar 19, 2007 at 4:16pm | Permalink
  6. Rob — I forget my exact repro, but I did find one where the trailing text inside a Run is stripped. Try:

    <Paragraph><Run>Hello </Run><Run> World</Run></Paragraph>
    Posted Mar 20, 2007 at 10:25am | Permalink