WPF Relative Binding using hierarchical collection structure
I have an ObservableCollection containing an ObservableCollection:
public class BooksDetailModel
{
public BookModel Book{ get; set; 开发者_如何学C}
public ObservableCollection<AuthorModel> Authors { get; set; }
}
Property in ViewModel:
public ObservableCollection<BooksDetailModel> Books { get; set; }
I would like to render this in a ListBox like this:
Book1
- Author1
- Author2
Book2
- Author1
etc.
The top level bind is easy but I am having trouble with the inner child collection.
XAML so far:
<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>
Any suggestions for ??? - Relative binding the inner listbox itemsource to the parent itemsource's Authors collection.
You should bind the ItemsSource
of the inner ListBox
to the Authors
property. And the binding in the DataTemplate
will be simply binding to the Name
property of the author:
<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>
精彩评论