c# - 如何在代码中绑定(bind)嵌套对象或主从绑定(bind)?

标签 c# .net wpf binding master-detail

我有三个嵌套类,节目、季节和剧集,其中节目有季节,季节有剧集。

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

我该怎么做?我更喜欢在代码中设置它,而不是 xaml,但如果您知道如何使用 xaml 进行设置,那总比没有好..

简化的 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";
  }
}

有人知道如何绑定(bind)第二个列表框吗?

最佳答案

编辑:添加更多细节。

好的,假设您有一个 Show 对象。这有一个季节的集合。每个季节都有一系列情节。然后,您可以让整个控件的 DataContext 成为 Show 对象。

  • 将您的 TextBlock 绑定(bind)到节目的名称。 Text="{绑定(bind)名称"}
  • 绑定(bind)季节的ItemsSource Seasons 集合的列表框。 ItemsSource="{绑定(bind)季节}" IsSynchronizedWithCurrentItem="真"
  • 绑定(bind)剧集的 ItemsSource 当前季节的列表框 剧集合集。 ItemsSource="{绑定(bind) 季/集}"。

假设您窗口的 DataContext 是 Show 对象,则 XAML 将是:

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

因此您的 UI 元素实际上并不需要名称。此外,将其转化为代码非常容易,而且您走在了正确的道路上。您的代码的主要问题是您在列表框并不真正需要的时候命名它们。

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

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

关于c# - 如何在代码中绑定(bind)嵌套对象或主从绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/508940/

相关文章:

c# - 创建 Web 服务器容器以模拟 IIS 服务器

c# - 是否可以从查询字符串中获取字典?

.net - 在哪里可以找到.net CLR和C#的源代码?

c# - TcpClient 收到数据时的事件

c# - 如何在 wpf 的组合框中将枚举值设置为 selectedItem

c# - 在 C# 中,是否保证任何给定线程都会看到另一个线程对引用类型变量的值所做的更新?

c# - 更改默认图标

c# - 为什么 WPF 中没有点击事件?

wpf - 为什么在嵌套 XAML 中编写时绑定(bind)语法不同

c# - 通过 CSOM 动态加载项目联机属性