Error on creating DataTemplate in code behind

时间:2015-08-07 02:42:35

标签: c# .net wpf xaml datatemplate

I'm trying to create a DataTemplate in code behind with the following:

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;

I get an XAML exception saying that 'x' is a space for a non declared name in line 5. I guess there's something wrong with x:Key=""adorner"", but it's strange because if instead of creating this in code I copy it and paste on the XAML it works!

I'm not sure this is the right way of doing it. The original code had the adorner resource in Window.Resources, but I didn't figured out how to access it when creating the DataTemplate in code, so I put it as a DataTemplate.Resource.

Does anyone have any clue on this?

1 个答案:

答案 0 :(得分:2)

包含命名空间:

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