C# 在代码隐藏中创建DataTemplate时出错

C# 在代码隐藏中创建DataTemplate时出错,c#,.net,wpf,xaml,datatemplate,C#,.net,Wpf,Xaml,Datatemplate,我正在尝试使用以下代码在代码隐藏中创建DataTemplate: StringReader stringReader = new StringReader( @"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation"" xmlns:local=""clr-namespace:Clarity.Demo.ListDragDrop;asse

我正在尝试使用以下代码在代码隐藏中创建DataTemplate:

StringReader stringReader = new StringReader(
    @"<DataTemplate      
        xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
        xmlns:local=""clr-namespace:Clarity.Demo.ListDragDrop;assembly=Clarity.Demo.ListDragDrop"">
        <DataTemplate.Resources>
           <local:PlayerAdorner x:Key=""adorner""/>
        </DataTemplate.Resources>
        <local:PlayerControl 
            Margin=""5""
            local:DragDropHelper.AdornerLayer = ""adornLayer""
            local:DragDropHelper.DragDropControl = ""{StaticResource adorner}""
            local:DragDropHelper.DropTarget = ""lineup""
            local:DragDropHelper.IsDragSource = ""true"" />
        </DataTemplate > ");

XmlReader xmlReader = XmlReader.Create(stringReader);
DataTemplate laneTemplate = XamlReader.Load(xmlReader) as DataTemplate;
StringReader StringReader=新建StringReader(
@"
");
XmlReader=XmlReader.Create(stringReader);
DataTemplate laneTemplate=XamlReader.Load(xmlReader)作为DataTemplate;
我得到一个XAML异常,表示“x”是第5行中未声明名称的空格。我猜
x:Key=”“adorner”“
有问题,但这很奇怪,因为如果不是在代码中创建它,而是复制它并粘贴到XAML上,它就可以工作了

我不确定这样做是否正确。最初的代码在Window.Resources中有adorner资源,但在代码中创建DataTemplate时我不知道如何访问它,所以我将其作为DataTemplate.resource


有人对此有任何线索吗?

包括名称空间:

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"