我正在使用 T4 模板生成数据模板。这是我正在使用的功能。
public static bool AppendDataTemplate(string filePath, string dataTemplateToBeAppended)
{
try
{
XmlNode newDataTemplateNode = CreateNodeFromXmlString(dataTemplateToBeAppended);
if (newDataTemplateNode != null)
{
if (newDataTemplateNode.Attributes != null)
{
string itemTemplateKey = newDataTemplateNode.Attributes["x:Key"].Value;
XmlElement resourceDictionaryRoot;
XmlDocument existingXmlDocument = GetRootDocumentFromFile(filePath, out resourceDictionaryRoot);
if (resourceDictionaryRoot != null)
{
if (
resourceDictionaryRoot.ChildNodes.Cast<XmlNode>()
.Any(
node =>
node.Attributes != null && node.Attributes["x:Key"].Value == itemTemplateKey))
{
return true;
}
if (resourceDictionaryRoot.OwnerDocument != null)
{
XmlNode importNode = resourceDictionaryRoot.OwnerDocument.ImportNode(
newDataTemplateNode,
true);
resourceDictionaryRoot.AppendChild(importNode);
}
}
else
{
throw new ApplicationException(
"There is some issue while getting xml from the specified file");
}
existingXmlDocument.Save(filePath);
}
}
else
{
throw new ApplicationException("There is some issue while converting specified string to XML");
}
}
catch (Exception ex)
{
throw;
}
return true;
}
private static XmlNode CreateNodeFromXmlString(string xml)
{
var newDataTemplateDocument = new XmlDocument();
newDataTemplateDocument.XmlResolver = null;
newDataTemplateDocument.LoadXml(xml);
return newDataTemplateDocument.DocumentElement;
}
这工作正常,但唯一的问题是,我必须添加 xml 命名空间以及数据模板,否则它会引发错误,无论如何我们可以停止 XML 验证吗?见下面的模板,如果我没有通过 xmlns 它会抛出验证错误..有什么建议吗?
<DataTemplate x:Key="PersonItemTemplate" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid HorizontalAlignment="Left" Width="250" Height="250">
<Border Background="{StaticResource ListViewItemPlaceholderBackgroundThemeBrush}">
<Image Source="{Binding ImageUrl}" Stretch="UniformToFill" />
</Border>
<StackPanel VerticalAlignment="Bottom" Background="{StaticResource ListViewItemOverlayBackgroundThemeBrush}">
<TextBlock Text="{Binding PersonName}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="40" Margin="15,0,15,0" />
<TextBlock Text="{Binding PersonId}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" Margin="15,0,15,10" />
<TextBlock Text="{Binding PersonAddress}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" Margin="15,0,15,10" />
<TextBlock Text="{Binding BirthDate}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" Margin="15,0,15,10" />
</StackPanel>
</Grid>
</DataTemplate>