【问题标题】:Problem in ListBox ItemTemplate binding using XML as itemssource使用 XML 作为 itemssource 的 ListBox ItemTemplate 绑定中的问题
【发布时间】:2010-06-23 20:57:10
【问题描述】:

我有点麻烦...

这是我的“mappings.xml”文件...

<?xml version="1.0" encoding="utf-8"?>
<mappings>
  <mapping QID="info1">
    <empty></empty>
  </mapping>
  <mapping QID="info2">
    <empty></empty>
  </mapping>
</mappings>

加载 XML 并将其设置为列表框的 ItemsSource 的方法:
(注意:我没有在 XAML 中使用 &lt;XMLDataProvider&gt;,因为它提供了一组 XML.XMLElement,而不是 LINQ-兼容XElement我想合作。

Private Property myCollectionView as CollectionView
Private Property mappingsEnum as IEnumerable(Of System.Xml.Linq.XElement)

    Sub LoadXML()
        mappingsEnum = XDocument.Load("mappings.xml").Root.Elements

        'using collection view so I can apply 
        'filtering to the list of <mapping> objects

         myCollectionView = CollectionViewSource.GetDefaultView(mappingsEnum)

        myListBox.ItemsSource = myCollectionView       
End Sub

在 XAML 中

<Grid>
   <ListBox x:Name="myListBox" ScrollViewer.VerticalScrollBarVisibility="Auto"   DockPanel.Dock="Bottom" ScrollViewer.CanContentScroll="True"   VirtualizingStackPanel.VirtualizationMode="Recycling"   VirtualizingStackPanel.IsVirtualizing="True" SelectionMode="Extended">
         <ListBox.ItemTemplate>
                        <DataTemplate>
                            <Grid>
                              <!--  WHY DOESN'T THIS WORK?? -->    
                              <TextBlock Text="{Binding XPath=@QID}">
                            </Grid>
                        </DataTemplate>
         </ListBox.ItemTemplate>
</ListBox>
</Grid>

我也尝试将 XPath 设置为“.@QID”,但没有任何区别。我检查了 myListBox.Items 集合并确认这些项目实际上是 XElement 对象,看起来像 &lt;mapping QID="..."&gt;&lt;empty/&gt;&lt;/mapping&gt; 所以我认为那里没有问题。

最终结果是一个用空对象填充的列表框。我可以过滤它们,对它们进行排序,并向它们添加非绑定文本……但是任何与源对象的绑定都不会被渲染。

【问题讨论】:

    标签: wpf listbox linq-to-xml datatemplate itemssource


    【解决方案1】:

    http://msdn.microsoft.com/en-us/library/system.windows.data.binding.xpath.aspx

    那里的一些引述:

    LINQ to XML 对象 XDocument 和 XElement 不使用 XPath。为了 详细信息,请参阅如何:绑定到 XDocument、XElement 或 LINQ for XML 查询结果。

    以及一些如何绑定到 XElement 的示例

    http://msdn.microsoft.com/en-us/library/cc165615.aspx

    【讨论】:

    • 啊啊啊啊。我一定已经看过那篇文章 3 遍了,从来没有一直读到最后。谢谢!
    • 最终的解决方案看起来像这样
    猜你喜欢
    • 2014-08-16
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多