Pastebin launched a little side project called VERYVIRAL.com, check it out ;-) Want more features on Pastebin? Sign Up, it's FREE!
Guest

C# ListBox from a lists of lists of objects (and deeper)

By: a guest on Feb 22nd, 2012  |  syntax: None  |  size: 1.25 KB  |  views: 17  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. namespace mySillyExample
  2. {
  3.   public class BookShelf
  4.   {
  5.     public Shelf[] myShelves{get; set;}
  6.   }
  7.  
  8.   public class Shelf
  9.   {
  10.     public Book[] booksOnThisShelf{get; set;}
  11.   }
  12.  
  13.   public class Book
  14.   {
  15.     public string Title {get; set;};
  16.     public string Author{get; set;};
  17.     public string ISBN {get; set;};
  18.   }
  19. }
  20.        
  21. <ListBox Height="154" HorizontalAlignment="Left"
  22.          ItemsSource="{Binding Path=BookShelf.myShelves}"                  
  23.          Margin="171,475,0,0" VerticalAlignment="Top" Width="333" >
  24.   <ListBox.ItemTemplate>
  25.     <DataTemplate>
  26.       <TextBlock Text="{Binding Path=booksOnThisShelf.[0].Title}" />
  27.     </DataTemplate>
  28.   <ListBox.ItemTemplate>
  29. </ListBox>
  30.        
  31. //ViewModelBase should be a base class that implements INotifyPropertyChanged
  32. public class MyViewModel : ViewModelBase
  33. {
  34.      public readonly IDataProvider _provider;
  35.  
  36.      public MyViewModel(IDataProvider provider)
  37.      {
  38.          _provider = provider ?? (some default provider);
  39.      }
  40.  
  41.      public IList<String> Titles
  42.      {
  43.          get
  44.          {
  45.               var q = from shelves in _provider.GetBookShelves()
  46.                       from books in shelves.booksOnThisShelf
  47.                       select books.Title;
  48.  
  49.               return q as List<String>;
  50.          }
  51.      }
  52. }