在 wpf mvvm 数据绑定菜单项中添加额外级别

Adding an extra level in wpf mvvm data bound menu item

我有一个名为 'Authors' 的菜单项,其 ItemsSource 绑定到名为 CollectionOfAuthorsObservableCollection。单击 Authors 打开作者姓名列表。我需要做哪些修改才能添加额外级别的菜单项,简单来说,我希望显示每个作者姓名的图书列表。

像这样:

Author
 |__AuthorName 1
    |__Book 1
    |__Book 2

这是我现有的代码:

MainWindow.xaml

<MenuItem Header="Authors" ItemsSource="{Binding CollectionOfAuthors}">
    <MenuItem.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding AuthorName}" />                                    
        </DataTemplate>
    </MenuItem.ItemTemplate>
</MenuItem>

MainWindowViewModel.cs

private ObservableCollection<Author> _collectionOfAuthors;

public ObservableCollection<Author> CollectionOfAuthors
{
    get { return _collectionOfAuthors; }
    set { SetProperty(ref _collectionOfAuthors, value); }
}

public class Author
{
   public string AuthorName {get; set;}

   private ObservableCollection<BookDetails> _Books;

   public ObservableCollection<BookDetails> Books
   {
       get { return _Books; }
       set { SetProperty(ref _Books, value); }
    }
}

为此使用 HierarchicalDataTemplate

<MenuItem Header="Authors" ItemsSource="{Binding CollectionOfAuthors}">
    <MenuItem.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=Books}">
            <TextBlock Text="{Binding AuthorName}"/>
            <HierarchicalDataTemplate.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding BookName}"/>
                </DataTemplate>
            </HierarchicalDataTemplate.ItemTemplate>
        </HierarchicalDataTemplate>
    </MenuItem.ItemTemplate>
</MenuItem>