【发布时间】:2010-05-11 06:57:56
【问题描述】:
我正在努力研究如何将 default 命名空间与 XmlDataProvider 和 XPath 绑定一起使用。
有一个使用本地名称<Binding XPath="*[local-name()='Name']" /> 的ugly answer,但这对于希望此 XAML 高度可维护的客户来说是不可接受的。
后备方案是强制他们在报告 XML 中使用非默认命名空间,但这是一个不可取的解决方案。
XML 报告文件如下所示。只有当我删除 xmlns="http://www.acme.com/xml/schemas/report 时它才会起作用,所以没有默认命名空间。
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type='text/xsl' href='PreviewReportImages.xsl'?>
<Report xsl:schemaLocation="http://www.acme.com/xml/schemas/report BlahReport.xsd" xmlns:xsl="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.acme.com/xml/schemas/report">
<Service>Muncher</Service>
<Analysis>
<Date>27 Apr 2010</Date>
<Time>0:09</Time>
<Authoriser>Service Centre Manager</Authoriser>
我使用 XAML 在窗口中展示的内容:
<Window x:Class="AcmeTest.ReportPreview"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ReportPreview" Height="300" Width="300" >
<Window.Resources>
<XmlDataProvider x:Key="Data"/>
</Window.Resources>
<StackPanel Orientation="Vertical" DataContext="{Binding Source={StaticResource Data}, XPath=Report}">
<TextBlock Text="{Binding XPath=Service}"/>
</StackPanel>
</Window>
使用用于将 XmlDocument 加载到 XmlDataProvider 中的代码隐藏(似乎是从文件或对象加载在运行时变化的唯一方法)。
public partial class ReportPreview : Window
{
private void InitXmlProvider(XmlDocument doc)
{
XmlDataProvider xd = (XmlDataProvider)Resources["Data"];
xd.Document = doc;
}
public ReportPreview(XmlDocument doc)
{
InitializeComponent();
InitXmlProvider(doc);
}
public ReportPreview(String reportPath)
{
InitializeComponent();
var doc = new XmlDocument();
doc.Load(reportPath);
InitXmlProvider(doc);
}
}
【问题讨论】:
-
无需测试,您应该能够使用 XmlNamespaceManager 作为绑定的一部分;那么你必须使用前缀,但它应该可以工作。
-
是的,强制前缀是我的后备方案,但这意味着很多 XSLT 外部脚本需要更改以适应默认命名空间。
标签: xaml binding xmldataprovider