如何在WPF ListBox项中显示ListBox绑定的XML文件中的节点数量?

时间:2014-05-29 06:41:58

标签: c# xml wpf listbox

我在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);
    }
}

MainWindow中有一个名为lbxCategory的ListBox。此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)

但我不知道该怎么做。我真诚地感谢您的帮助。请。

1 个答案:

答案 0 :(得分:0)

如果你最终在后面的代码中手动解析你的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>