views:

1375

answers:

1

I have a three nested classes, Show, Season and Episode, where a show has seasons, and seasons has episodes.

I want to bind two listboxes so that the first lists seasons, and the second lists episodes in that season.

How can I do this? I prefer to set this up in code, not xaml, but if you know how to do it with xaml, it's better than nothing..

A simplifyed xaml:

<Window>
  <Label name="Showname" />
  <ListBox name="Seasons" />
  <ListBox name="Episodes" />
</Window>

and some relevant code:

public partial class Window1 : Window
{
  public Data.Show show { get; set; }
  public Window1()
  {
    this.DataContex = show;

    //Bind shows name to label
    Binding bindName = new Binding("Name");
    ShowName.SetBinding(Label.ContentProperty, bindName);

    //Bind shows seasons to first listbox
    Binding bindSeasons = new Binding("Seasons");
    Seasons.SetBinding(ListBox.ItemsSourceProperty, bindSeasons);
    Seasons.DisplayMemberPath = "SeasonNumber";
    Seasons.IsSyncronizedWithCurrentItem = true;

    //Bind current seasons episodes to second listbox
    Binding bindEpisodes = new Binding("?????");
    Episodes.SetBinding(ListBox.ItemsSourceProperty, bindEpisodes);
    Episodes.DisplayMemberPath = "EpisodeTitle";
  }
}

Anyone got any clues how to bind up the second listbox?

+4  A: 

Edit: adding a bit more details.

Ok, so let's say you have a Show object. This has a collection of Seasons. Each Season has a collection of Episodes. You can then have the DataContext for the entire control be the Show object.

  • Bind your TextBlock to the show's Name. Text="{Binding Name"}
  • Bind the ItemsSource of the seasons list box to the Seasons collection. ItemsSource="{Binding Seasons}" IsSynchronizedWithCurrentItem="True"
  • Bind the ItemsSource of the episodes list box to the current Season's Episodes collection. ItemsSource="{Binding Seasons/Episodes}".

Assuming your Window's DataContext is the Show object, the XAML would be:

<Window>
   <TextBlock Text="{Binding Name}" />
   <ListBox ItemsSource="{Binding Seasons}" IsSynchronizedWithCurrentItem="True" />
   <ListBox ItemsSource="{Binding Seasons/Episodes}" />   
</Window>

So your UI elements don't really need names. Also, to translate this into code is pretty easy and you were on the right path. The main issue with your code was that you were naming the list boxes, when they don't really need it.

Assuming the Season object has a property called Episodes, which is a collection of Episode objects, I think it is:

 Binding bindEpisodes = new Binding("Seasons/Episodes");
siz
Man, that was fast! And simple, and correct.Thanks!
Vegar