【问题标题】:Listbox content not being populated with content from xml when using XmlDataProvider使用 XmlDataProvider 时未使用来自 xml 的内容填充列表框内容
【发布时间】:2011-03-18 16:44:35
【问题描述】:

我有一个非常简单的应用程序资源指定为

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

然后是一个窗口试图用来自 xml 的元素填充列表视图

<ListBox x:Name="lbColor" 
                 IsSynchronizedWithCurrentItem="True"
                 Width="248" Height="56"
                 ItemsSource="{Binding Source={StaticResource MoreColors}, XPath=color/@name}">

        </ListBox> 

但是在运行时,应用程序根本不会填充 Listview。我不敢相信我还没有能够让这么简单的事情起作用....

【问题讨论】:

    标签: wpf listbox xmldataprovider


    【解决方案1】:

    尝试在应用资源中使用&lt;colors xmlns=""&gt;而不是&lt;colors&gt;

    http://msdn.microsoft.com/en-us/library/system.windows.data.xmldataprovider.aspx 说 “XML 数据的根节点有一个 xmlns 属性,该属性将 XML 命名空间设置为空字符串。这是将 XPath 查询应用于 XAML 页面内联的数据岛的要求。在这种内联情况下,XAML,因此数据岛继承了 System.Windows 命名空间。因此,您需要将命名空间设置为空白,以防止 XPath 查询被 System.Windows 命名空间限定,这会误导查询。”

    【讨论】:

      【解决方案2】:

      请检查以下更改是否适合您:

      为数据提供者添加了一个空的命名空间到颜色节点:

      <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 查询略有改变:

      <ListBox ItemsSource="{Binding Source={StaticResource MoreColors}, XPath=//color/@name}" />
      

      希望这会有所帮助,问候

      【讨论】:

        猜你喜欢
        • 2013-02-01
        • 1970-01-01
        • 2011-02-09
        • 2022-06-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多