Listbox content not being populated with content f

2019-08-15 20:38发布

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....

2条回答
我命由我不由天
2楼-- · 2019-08-15 21:07

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."

查看更多
放我归山
3楼-- · 2019-08-15 21:09

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

查看更多
登录 后发表回答