如何在WPF列表框项中显示列表框绑定到的XML文件中的节点数量

本文关键字:列表 XML 文件 节点 显示 WPF 绑定 | 更新日期: 2023-09-27 18:05:45

我用c#编写了一个WPF应用程序。这里有一个XML文件Book.xml。该文件如下所示:

<?xml version="1.0" encoding="utf-8" ?>
<Books xmlns="">
  <Category name="Computer Programming">
    <Book>
      <Author>H. Schildt</Author>
      <Title>C# 4.0 The Complete Reference</Title>
    </Book>
  </Category>
  <Category name="Art Editions">
    <Book>
      <Author>M. Cervantes</Author>
      <Title>The Ingenious Gentleman Don Quixote of La Mancha </Title>
    </Book>
    <Book>
      <Author>P. Ronsard</Author>
      <Title>Les Amours</Title>
    </Book>
  </Category>
</Books>

在应用程序主窗口的构造函数中,我计算每个Category节点中Book节点的数量。我是这样做的:

// List of entries of <Book> nodes within each <Category> node
// this list is the private field of MainWindow class.
private List<Int32> bookNodeEntriesList = new List<int>();
public MainWindow()
{
    InitializeComponent();
    // Derive a content of XML file "Books.xml".
    var doc = XDocument.Parse("path_to_Books.xml");
    // Loop through all <Category> nodes.
    foreach (var category in doc.Root.Elements("Category"))
    {
        // Count <Book> nodes within current <Category> node.
        var numberOfBooks = category.Elements("Book").Count();
        // Save the calculated quantity in the list.
        bookNodeEntriesList.Add(numberOfBooks);
    }
}
在主窗口中有一个名为lbxCategory的列表框。这个ListBox通过XMLDataProvider绑定到Books.xml文件。下面我显示了与它相关的XAML标记。
<Window x:Class="BookCatalogue.MainWindow"
. . . . . . .
    <Window.Resources>
        <!--This XMLDataProvider uses file Books.xml as data source-->
        <XmlDataProvider x:Key="MyList" Source="Data'Books.xml"
                         XPath="Books/Category"/>
        <!--This is data template for ListBox-->
        <DataTemplate x:Key="masterDataTemplate">
            <TextBlock Text="{Binding XPath=@name}" />
        </DataTemplate>
    </Window.Resources>
. . . . . . .
    <!--This ListBox shows master-level data-->
    <ListBox Name="lbxCategory" Grid.Row="0" Grid.Column="0" 
             ItemsSource="{Binding Source={StaticResource MyList}}"
             ItemTemplate="{StaticResource masterDataTemplate}"
             IsSynchronizedWithCurrentItem="true"
             SelectionChanged="lbxCategory_SelectionChanged"/>
. . . . . . .
</Window>

我需要获取bookNodeEntriesList的每个元素,并将其显示在lbxCategory ListBox的适当项中,位于括号内图书类别名称的右侧。例如:

ComputerProgramming   (1)
Art Editions          (2)

但是我不知道怎么做。我将由衷地感谢你的帮助。请。

如何在WPF列表框项中显示列表框绑定到的XML文件中的节点数量

如果您最终在后面的代码中手动解析xml文件,那么最好创建一个模型并将ListBox绑定到它的集合。

public class CategoryModel
{
    public string Name { get; set; }
    public int BookCount { get; set; }
}
public MainWindow()
{
    BookCategories = new ObservableCollection<CategoryModel>();
    var doc = XDocument.Parse("path_to_Books.xml");
     // Loop through all <Category> nodes.
     foreach (var category in doc.Root.Elements("Category"))
     {
          // Count <Book> nodes within current <Category> node.
            var numberOfBooks = category.Elements("Book").Count();
           // Save the calculated quantity in the list.
             BookCategories.Add(new CategoryModel { Name = category.Attribute("name").Value, BookCount = numberOfBooks });
      }
      InitializeComponent();
}

 public ObservableCollection<CategoryModel> BookCategories { get; set; }
在Xaml:

<ListBox Name="lbxCategory" Grid.Row="0" Grid.Column="0" 
             ItemsSource="{Binding BookCategories }"
             IsSynchronizedWithCurrentItem="true"
             SelectionChanged="lbxCategory_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Name}"></TextBlock>
                        <Label Content="("></Label>
                        <Label Content="{Binding BookCount}"></Label>
                        <Label Content=")"></Label>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>