2009-02-03 65 views
3

我有三个嵌套类,Show,Season和Episode,一个节目有季节,季节有剧集。如何在代码中绑定嵌套对象或主控细节绑定?

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

我该怎么做?我更喜欢在代码,而不是XAML对此进行设置,但如果你知道如何使用XAML做到这一点,它总比没有好..

一个simplifyed XAML:

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

和一些相关代码:

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"; 
    } 
} 

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

回答

8

编辑:添加更多的细节。

好吧,让我们假设你有一个Show对象。这有一个季节的集合。每季都有一集情节。然后您可以将整个控件的DataContext作为Show对象。

  • 将您的TextBlock绑定到节目的名称。 Text =“{Binding Name”}
  • 将季节的ItemsSource 列表框绑定到Seasons集合。 的ItemsSource =“{结合四季}” IsSynchronizedWithCurrentItem =“真”
  • 绑定发作的ItemsSource 列表框中当前季节的 情节集合。 ItemsSource =“{Binding Seasons/Episodes}”。

假设你的窗口的DataContext的是显示对象时,XAML是:

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

所以,你的UI元素并不真正需要的名字。而且,将其转换成代码非常简单,而且您的方法正确。你的代码的主要问题是你在命名列表框时,当他们不需要它时。

假设季节对象有一个名为情节属性,它是集对象的集合,我觉得是:

Binding bindEpisodes = new Binding("Seasons/Episodes"); 
+0

人,那是快!简单,正确。 谢谢! – Vegar 2009-02-03 21:26:38