The view model contains a list with ObservableCollection<Book>

 public class VM { public ObservableCollection<Book> bookList { get; set; } } 

книга in turn contains a список с рассказами

 public class Book { public string Name { get; set;} public ObservableCollection<Story> storyList { get; set; } } 

The story has a title and number of pages.

 public class Story { public string Name {get;set;} public int CountPage {get;set;} } 

The question is how to properly bind to the Name and CountPage ?

 <DataGrid ItemsSource="{Binding bookList}"> <DataGrid.Columns> <DataGridTextColumn Header="Рассказ" Binding="{Binding Name}"/> <DataGridTextColumn Header="Количество страниц" Binding="{Binding CountPage}"/> </DataGrid.Columns> </DataGrid> 
  • one
    It all depends on how you want to display the content. The book has many stories, each story has its own number of pages. I think, DataGrid, it doesn't quite fit here, you probably need a TreeView. Or include the TreeView in the Details of each Row from the DataGrid (i.e. each book). You can use the HierachicalDataTemplate. - klutch1991

1 answer 1

You can try something like this:

 <DataGrid ItemsSource="{Binding bookList}"> <DataGrid.RowDetailsTemplate> <DataTemplate> <TreeView ItemsSource="{Binding storyList}"> <TreeView.Resources> <HierarchicalDataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Name}"/> <TextBlock Text="{Binding CountPage}"/> </StackPanel> </HierarchicalDataTemplate> </TreeView.Resources> </TreeView> </DataTemplate> </DataGrid.RowDetailsTemplate> <DataGrid.Columns> <DataGridTextColumn Header="Рассказ" Binding="{Binding Name}"/> <DataGridTextColumn Header="Количество страниц" Binding="{Binding CountPage}"/> </DataGrid.Columns> </DataGrid> 

The template for Details itself is, of course, designed by yourself (somehow more visually). But I think this code should push you to the general idea.

PS public properties of your ViewModel better to name with a capital letter. From the lowercase letters, as a rule, referred to as closed fields.

  • The idea with rowdetailtemplate is clear, but in this case, for detail to work, you need to display a list of books to begin with, because it is displayed by pressing a row. And for this you need to get attached to something from the very bookList, - Gardes
  • Well, if you need to immediately display the entire tree, use TreeView without a DataGrid once. And set IsExpanded to true . In your model classes, one way or another, a hierarchical structure is viewed. - klutch1991
  • Unsubscribe when I try, thanks - Gardes
  • I did it completely through TreeView, it helped me, your idea is correct, but the code has errors. - Gardes
  • @ S.KosT, in the studio did not check, therefore inaccuracies in the markup code are possible. Glad you helped. - klutch1991