Creation of DataTemplate in code-behind fails <p>I'm trying to create a <code>DataTemplate</code> in my code and I came across <a href="http://stackoverflow.com/a/7171332/1094430">this asnwer</a>.</p> <p>So I just copied and edited the code, but it fails with this exception:</p> <blockquote> <p>First-chance exception 'System.Windows.Markup.XamlParseException' in System.Windows.ni.dll Unknown parser error: Scanner 2147500037. [Line: 4 Position: 36]</p> </blockquote> <p>Here's the generated XAML code:</p> <pre><code>&lt;DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:simplebackground="clr-namespace:Plugins.Backgrounds.SimpleBackground"&gt; &lt;simplebackground:SimpleBackground/&gt; &lt;/DataTemplate&gt; </code></pre> <p>and here's the XAML code that I'm currently using in my page (this one's working):</p> <pre><code>&lt;phone:PhoneApplicationPage xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:simpleBackground="clr-namespace:Namespace.Backgrounds.SimpleBackground" x:Class="Namespace.Backgrounds.SimpleBackground.SimpleBackground" mc:Ignorable="d" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" d:DesignHeight="480" d:DesignWidth="480"&gt; &lt;phone:PhoneApplicationPage.Resources&gt; &lt;DataTemplate x:Key="DataTemplate"&gt; &lt;simpleBackground:SimpleBackground /&gt; &lt;/DataTemplate&gt; &lt;/phone:PhoneApplicationPage.Resources&gt; ............. &lt;phone:PhoneApplicationPage&gt; </code></pre> <p>To generate the XAML I'm using this C# code:</p> <pre><code>public static DataTemplate Create(Type type) { var templateString = "&lt;DataTemplate\r\n" + "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\r\n" + "xmlns:" + type.Name.ToLowerInvariant() + "=\"clr-namespace:" + type.Namespace + "\"&gt;\r\n" + "&lt;" + type.Name.ToLowerInvariant() + ":" + type.Name + "/&gt;\r\n" + "&lt;/DataTemplate&gt;"; return XamlReader.Load(templateString) as DataTemplate; } </code></pre> <p>What's wrong with it? The exception's message is not that useful :(</p>