运行WPF应用程序,其中控件绑定到XML数据

时间:2011-12-17 17:00:08

标签: wpf xml xaml data-binding build

我使用以下XAML文件创建XML资源,然后将此资源绑定到列表框:

<Window x:Class="WpfPractice.HierarchicalData"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="HierarchicalData" Height="200" Width="650">
    <Window.Resources>
        <XmlDataProvider x:Key="XMLItems" XPath="/colors/color/@name">
            <x:XData>
                <colors >
                    <color name="pink"/>
                    <color name="white"/>
                    <color name="black"/>
                 </colors>
            </x:XData>
        </XmlDataProvider>
    </Window.Resources>
    <Grid>
          <ListBox ItemsSource="{Binding Source={StaticResource XMLItems}}"/>
    </Grid>
</Window>

VS设计器显示颜色列表没有任何问题,但是当我调试WPF应用程序时,窗口是空的。事实上,当我尝试将任何XML项绑定到WPF控件时,我遇到了同样的问题。有什么建议吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

您应该重置默认的namesapce:

<colors xmlns="">

MSDN

  

XML数据的根节点具有xmlns属性,该属性将XML命名空间设置为空字符串。这是将XPath查询应用于XAML页面内联的数据岛的要求。在此内联案例中,XAML以及数据岛继承了System.Windows命名空间。因此,您需要将命名空间设置为空,以防止XPath查询被System.Windows命名空间限定,这会误导查询。