gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:05:14 27 4
gpt4 key购买 nike

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

我想绑定(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)季节的ItemsSourceSeasons 集合的列表框。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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com