How do I bind to XmlDataProvider whos source has a default namespace (xmlns) set?
I have XML similar to the following
<?xml version="1.0" encoding="utf-8"?>
<foo name="FooBar" xmlns="http://mydomain/myapp/ver/myschema.xsd">
<bars v="test">
<bar bat="one"/>
<bar bat="two"/>
<bar bat="three"/>
</bars>
</foo>
How do I map this in WPF, it works if I don't set the default namespace, however when I have xmlns
set my binding does not match anything. I have tried the following declarations however I'm having trouble figuring out how to map the combo box as shown below.
<Window.Resources>
<!-- works if xmlns is not set -->
<XmlDataProvider x:Ke开发者_Go百科y="mySource1"
XPath="/foo">
<!-- also tried -->
<XmlDataProvider x:Key="mySource2"
XPath="//*[local-name()='foo']">
<!-- also tried -->
<XmlDataProvider x:Key="mySource3"
XPath="/foo">
<XmlDataProvider.XmlNamespaceManager>
<XmlNamespaceMappingCollection>
<XmlNamespaceMapping
Uri="http://mydomain/myapp/ver/myschema.xsd"
Prefix=""/>
</XmlNamespaceMappingCollection>
</XmlDataProvider.XmlNamespaceManager>
</XmlDataProvider>
</Window.Resources>
<StackPanel DataContext="{StaticResource mySource1}">
<Label Content="{Binding XPath=@name}"/>
<Label DataContext="{Binding XPath=bars}"
Content="{Binding XPath=@v}"/>
</StackPanel>
I'm assigning the XmlDataProvider.Source
property through the following code.
XmlDataProvider xdp = FindResource("mySource1") as XmlDataProvider;
// ... setup dialog and confirm resource.
using (Stream s = dlg.OpenFile()) {
XmlDocument doc = new XmlDocument();
doc.Load(s);
xdp.Document = doc;
}
Any help solving this would be very much appreciated, thanks.
UPDATE
From Andrews suggestion I've come up with the following:
<Window.Resources>
<XmlDataProvider x:Key="mySource"
XPath="/fb:foo">
<XmlDataProvider.XmlNamespaceManager>
<XmlNamespaceMappingCollection>
<XmlNamespaceMapping
Uri="http://mydomain/myapp/ver/myschema.xsd"
Prefix="fb"/>
</XmlNamespaceMappingCollection>
</XmlDataProvider.XmlNamespaceManager>
</XmlDataProvider>
</Window.Resources>
<StackPanel DataContext="{StaticResource mySource}">
<Label Content="{Binding XPath=@name}"/>
<ComboBox ItemsSource="{Binding XPath=fb:bars/fb:bar}"
IsSynchronizedWithCurrentItem="True">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding XPath=@bat}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
Can you try this ? I am not too familiar with xml namespaces.
<Window.Resources>
<!-- also tried -->
<XmlDataProvider x:Key="mySource3"
XPath="/cs:foo">
<XmlDataProvider.XmlNamespaceManager>
<XmlNamespaceMappingCollection>
<XmlNamespaceMapping
Uri="http://mydomain/myapp/ver/myschema.xsd"
Prefix="cs"/>
</XmlNamespaceMappingCollection>
</XmlDataProvider.XmlNamespaceManager>
</XmlDataProvider>
</Window.Resources>
<StackPanel DataContext="{StaticResource mySource1}">
<Label Content="{Binding XPath=@name}"/>
<Label Content="{Binding XPath=cs:bat}"/>
</StackPanel>
精彩评论