DotNetSpartan
DotNetSpartan

Reputation: 1001

Adding an extra level in wpf mvvm data bound menu item

I've a menu item named 'Authors' whose ItemsSource is bound to an ObservableCollection called CollectionOfAuthors. Clicking on Authors opens a list of author names. What modifications I need to do to add an extra level of menu item, In simple words, I wish to display list of books for each author-name.

Like this:

Author
 |__AuthorName 1
    |__Book 1
    |__Book 2

Here's my existing code:

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

Upvotes: 0

Views: 41

Answers (1)

dhilmathy
dhilmathy

Reputation: 2868

Use HierarchicalDataTemplate for this.

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

Upvotes: 2

Related Questions