【问题标题】:WPF Relative Binding using hierarchical collection structure使用分层集合结构的 WPF 相对绑定
【发布时间】:2011-07-10 12:22:56
【问题描述】:

我有一个包含 ObservableCollection 的 ObservableCollection:

public class BooksDetailModel
{
    public BookModel Book{ get; set; }
    public ObservableCollection<AuthorModel> Authors { get; set; }
}

ViewModel 中的属性:

public ObservableCollection<BooksDetailModel> Books { get; set; }

我想像这样在 ListBox 中呈现它:

书1

  • 作者1
  • 作者2

书2

  • 作者1

等等

顶级绑定很简单,但内部子集合有问题。

XAML 到目前为止:

                <ListBox ItemsSource="{Binding Books}" BorderBrush="{x:Null}">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Vertical">
                            <TextBlock Text="{Binding Book.Name}" FontSize="12" FontWeight="Bold" />
                            <ListBox>
                                <ListBox.ItemTemplate>
                                    <DataTemplate>
                                        <TextBlock Text="{Binding ???, Path=Author.Name}" FontSize="10" />
                                    </DataTemplate>
                                </ListBox.ItemTemplate>
                            </ListBox>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>

有什么建议吗??? - 将内部列表框 itemsource 相对绑定到父 itemsource 的 Authors 集合。

【问题讨论】:

  • 你应该使用 HierarchicalDataTemplate

标签: wpf xaml data-binding


【解决方案1】:

您应该将内部ListBoxItemsSource 绑定到Authors 属性。而DataTemplate 中的绑定将简单地绑定到作者的Name 属性:

<ListBox ItemsSource="{Binding Books}" BorderBrush="{x:Null}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Vertical">
                <TextBlock Text="{Binding Book.Name}" FontSize="12" FontWeight="Bold" />
                <ListBox ItemsSource="{Binding Authors}">
                    <ListBox.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Name}" FontSize="10" />
                        </DataTemplate>
                    </ListBox.ItemTemplate>
                </ListBox>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

【讨论】:

  • 谢谢 - 我一直对 xaml 绑定的灵活性感到惊讶。我认为这可能与RelativeSource有关。
猜你喜欢
  • 1970-01-01
  • 2012-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 2016-02-28
相关资源
最近更新 更多