2014-01-08 30 views
1

我正在嘗試在我的代碼中創建DataTemplate,並且我遇到了this asnwer在代碼隱藏中創建DataTemplate失敗

所以我只是複製和編輯的代碼,但它失敗與此異常:

First-chance exception 'System.Windows.Markup.XamlParseException' in System.Windows.ni.dll Unknown parser error: Scanner 2147500037. [Line: 4 Position: 36]

這裏的生成XAML代碼:

<DataTemplate 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:simplebackground="clr-namespace:Plugins.Backgrounds.SimpleBackground"> 
    <simplebackground:SimpleBackground/> 
</DataTemplate> 

和這裏的XAML代碼,我目前使用我的網頁(這個工作):

<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"> 

    <phone:PhoneApplicationPage.Resources> 
     <DataTemplate x:Key="DataTemplate"> 
      <simpleBackground:SimpleBackground /> 
     </DataTemplate> 
    </phone:PhoneApplicationPage.Resources> 
    ............. 
<phone:PhoneApplicationPage> 

要生成XAML我使用這個C#代碼:

public static DataTemplate Create(Type type) 
{ 
    var templateString = "<DataTemplate\r\n" + 
         "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\r\n" + 
         "xmlns:" + type.Name.ToLowerInvariant() + "=\"clr-namespace:" + type.Namespace + "\">\r\n" + 
         "<" + type.Name.ToLowerInvariant() + ":" + type.Name + "/>\r\n" + 
         "</DataTemplate>";    
    return XamlReader.Load(templateString) as DataTemplate; 
} 

它有什麼問題? 異常的消息是沒有多大用處:(

回答

0

CreatetemplateString包含一個元素的XamlReader找不到你必須加入該元素所在的命名空間的組件:

public static DataTemplate Create(Type type) 
{ 
    var templateString = 
     "<DataTemplate " + 
      "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +         
      "xmlns:" + type.Name.ToLowerInvariant() + 
       "=\"clr-namespace:" + type.Namespace + 
       ";assembly=" + type.Assembly.GetName().Name + "\">" + 
     "<" + type.Name.ToLowerInvariant() + ":" + type.Name + "/>" + 
     "</DataTemplate>";    
    return XamlReader.Load(templateString) as DataTemplate; 
} 
+0

我我會嘗試它,但是我在創建這個代碼的同一個程序集中創建了我正在創建的元素! – StepTNT