0
votes

I have models structure like this:

public class Book
{
    public List<Author> Authors { get; set; }

    public Book()
    {
        Authors = new List<Authors>();
    }
}

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

I want somehow show the list of Books in 2 datagrids in WPF - One datagrid with books themself, when i select a row there - in second datagrids appears a list of Authors of the selected book.

How can I implement this? Probably I should use ObservableCollection, but how bind List to ObservableCollection?

3

3 Answers

3
votes

You should be having a ViewModel which has a collection of Books property and a SelectedBook property.

public class ViewModel
{
    public List<Book> Books { get; set; }

    public Book SelectedBook { get; set; }
}

And the XAML goes like below,

    <DataGrid ItemsSource="{Binding Books}"
              SelectedItem="{Binding SelectedBook, Mode=TwoWay}"/>
    <DataGrid ItemsSource="{Binding SelectedBook.Authors}"/>
3
votes

in addition to the answer from XAML Lover. if you dont want the SelectedBook in your Viewmodel and just do it in your view you can use the following binding

<DataGrid x:Name="books" ItemsSource="{Binding Books}"/>
<DataGrid ItemsSource="{Binding ElementName=books,Path=SelectedItem.Authors}"/>
0
votes

Ok - from what I understand of your question - you have two grids side by side ( Say BooksGrid and AuthorsGrid)

Click on a row in the BookGrid should lead to the authors of that Book to show on the AuthorsGrid.

If you are using MVVM - @XAML Lover's reply should work. If not using MVVM - handle the DataGrid.Selected event in the code behind, from the selected row - get your book element and set the AuthorsGrid.ItemSource to the authors of the selected book.

Should be simple.