如何在代码中绑定嵌套对象或master-detail-binding?

Veg*_*gar 3 .net c# wpf binding master-detail

我有三个嵌套课程,Show,Season和Episode,其中一个节目有季节,季节有剧集.

我想绑定两个列表框,以便第一个列出季节,第二个列出该季节的剧集.

我怎样才能做到这一点?我更喜欢在代码中设置它,而不是xaml,但如果你知道如何使用xaml,它总比没有好.

简化的xaml:

<Window>
  <Label name="Showname" />
  <ListBox name="Seasons" />
  <ListBox name="Episodes" />
</Window>
Run Code Online (Sandbox Code Playgroud)

和一些相关的代码:

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";
  }
}
Run Code Online (Sandbox Code Playgroud)

任何人都有任何线索如何绑定第二个列表框?

Szy*_*zga 8

编辑:添加更多细节.

好的,所以假设你有一个Show对象.这里有一系列季节.每个季节都有一系列剧集.然后,您可以将整个控件的DataContext设置为Show对象.

  • 将TextBlock绑定到节目的名称.Text ="{Binding Name"}
  • 将Seasons季节列表框的ItemsSource绑定到Seasons集合.ItemsSource ="{Binding Seasons}"IsSynchronizedWithCurrentItem ="True"
  • 将剧集列表框的ItemsSource绑定到当前Season的剧集集合.ItemsSource ="{Binding Seasons/Episodes}".

假设您的Window的DataContext是Show对象,XAML将是:

<Window>
   <TextBlock Text="{Binding Name}" />
   <ListBox ItemsSource="{Binding Seasons}" IsSynchronizedWithCurrentItem="True" />
   <ListBox ItemsSource="{Binding Seasons/Episodes}" />   
</Window>
Run Code Online (Sandbox Code Playgroud)

所以你的UI元素并不需要名字.此外,将其转换为代码非常简单,而且您走的是正确的道路.您的代码的主要问题是,当您不真正需要时,您正在命名列表框.

假设Season对象有一个名为Episodes的属性,它是Episode对象的集合,我认为它是:

 Binding bindEpisodes = new Binding("Seasons/Episodes");
Run Code Online (Sandbox Code Playgroud)