C# 在代码隐藏中创建DataTemplate失败
我试图在我的代码中创建一个C# 在代码隐藏中创建DataTemplate失败,c#,xaml,windows-phone-8,datatemplate,datatemplateselector,C#,Xaml,Windows Phone 8,Datatemplate,Datatemplateselector,我试图在我的代码中创建一个DataTemplate,我遇到了一个问题 所以我只是复制并编辑了代码,但它失败了,出现了以下异常: System.Windows.ni.dll中的首次异常“System.Windows.Markup.XamlParseException” 未知分析器错误:扫描程序2147500037。[第4行位置:36] 以下是生成的XAML代码: <DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/
DataTemplate
,我遇到了一个问题
所以我只是复制并编辑了代码,但它失败了,出现了以下异常:
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代码(这一个正在运行):
.............
要生成XAML,我将使用以下C代码:
公共静态数据模板创建(类型)
{
var templateString=“\r\n”+
“\r\n”+
"";
返回XamlReader.Load(templateString)作为DataTemplate;
}
怎么了?
异常的消息没有那么有用:(
Create
中的templateString
包含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;
}
公共静态数据模板创建(类型)
{
var templateString=
"" +
"" +
"";
返回XamlReader.Load(templateString)作为DataTemplate;
}
我会试试看,但我正在我试图创建的元素所在的程序集中创建此代码!
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;
}
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;
}