Effect of XML:Space=”preserve”
I was working with XAML created by Expression Blend. At runtime I noticed that a TextBlock moved on the right and one line down from the position it was in the designer. It took me some time to find the cause of the discrepancy. Below there is XAML of two TextBlock elements:
<TextBlock Height="17" VerticalAlignment="Top" xml:space="preserve"><Run xml:space="preserve">first line</Run></TextBlock> <TextBlock Margin="0,22,0,0" Height="23" VerticalAlignment="Top"> Second line </TextBlock>
In the designer it looks like this:
When the application is running, the picture is different:
As you see, the second line moved on the right and one line down.
The only unusual part of XAML is the xml:space=”preserve” attribute, which is set at the first TextBlock and the Run elment inside it. This attribute says that all the indentation and spaces in XAML code should be saved at the time of rendering. But according to MSDN the attribute scope is only the content of the element where the attribute is defined. It’s defined at the first TextBlock and the contained Run element. If you remove the attribute from those elements everything renders correctly. But why does the attribute from the first TextBlock influences the second TextBlock. In the debugger I stopped the application and saved XAML of the “second line” TextBlock and it really had xml:space=”preserve” attribute. I assume it somehow came from the “first line” TextBlock.
It is apparently a bug in WPF. The bug only apears If you have more than one nested elements with the xml:space =”preserve” attribute defined at both. The next sibling element after those will have this attribute set to “preserve” implicitly.
The solution is simple: you need to set xml:space=”default” explicitly at the next element. So our XAML will be:
<TextBlock Height="17" VerticalAlignment="Top" xml:space="preserve"><Run xml:space="preserve">first line</Run></TextBlock> <TextBlock Margin="0,22,0,0" Height="23" VerticalAlignment="Top" xml:space="default"> Second line </TextBlock>
No comments yet.
Leave a comment
-
Recent
- Remote desktop via VPN from SUSE 11.1
- EVPO DC project structure
- EVPODC Getting Started Part 2 (Configuration)
- EVPODC getting started part 1 (installation)
- Customize property editor in the VS designer
- How to load referenced assemblies from any place you want
- The puzzle about a car and two goats
- Effect of XML:Space=”preserve”
- regular expressions for XML tags
-
Links
-
Archives
- May 2009 (2)
- November 2008 (2)
- June 2008 (5)
-
Categories
-
RSS
Entries RSS
Comments RSS

