问题
I have a very simple application resource specified as
<Application.Resources>
<XmlDataProvider x:Key="MoreColors" XPath="/colors">
<x:XData>
<colors>
<color name="pink"/>
<color name="white"/>
<color name="black"/>
<color name="cyan"/>
<color name="gray"/>
<color name="magenta"/>
</colors>
</x:XData>
</XmlDataProvider>
</Application.Resources>
and then a window trying to populate a listview with elements from the xml as
<ListBox x:Name="lbColor"
IsSynchronizedWithCurrentItem="True"
Width="248" Height="56"
ItemsSource="{Binding Source={StaticResource MoreColors}, XPath=color/@name}">
</ListBox>
But when run the application does not populate the Listview at all. I cannot believe I havent been able to get something as simple as this to work....
回答1:
try using <colors xmlns="">
instead of<colors>
in applicaiton resource
http://msdn.microsoft.com/en-us/library/system.windows.data.xmldataprovider.aspx says "The root node of the XML data has an xmlns attribute that sets the XML namespace to an empty string. This is a requirement for applying XPath queries to a data island that is inline within the XAML page. In this inline case, the XAML, and thus the data island, inherits the System.Windows namespace. Because of this, you need to set the namespace blank to keep XPath queries from being qualified by the System.Windows namespace, which would misdirect the queries."
回答2:
Pls check if changes below would work for you:
for the data provider added an empty namespace to the colors node:
<XmlDataProvider x:Key="MoreColors" XPath="/colors">
<x:XData>
<colors xmlns="">
<color name="pink"/>
<color name="white"/>
<color name="black"/>
<color name="cyan"/>
<color name="gray"/>
<color name="magenta"/>
</colors>
</x:XData>
</XmlDataProvider>
xpath query slightly changed for the listbox:
<ListBox ItemsSource="{Binding Source={StaticResource MoreColors}, XPath=//color/@name}" />
hope this helps, regards
来源:https://stackoverflow.com/questions/5355162/listbox-content-not-being-populated-with-content-from-xml-when-using-xmldataprov