我正在尝试在代码中创建DataTemplate
,但我遇到了this asnwer。
所以我只是复制并编辑了代码,但它失败了,但是这个例外:
System.Windows.ni.dll中的第一次机会异常'System.Windows.Markup.XamlParseException' 未知的解析器错误:扫描程序2147500037. [行:4位置: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 :(得分:0)
templateString
中的Create
包含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;
}