Listbox content not being populated with content from xml when using XmlDataProvider

喜夏-厌秋 提交于 2019-12-11 06:18:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!