我正在尝试使用ListBox的ItemTemplate将属性ObservableCollection<ObservableCollection<Location>>
绑定到ListBox,而ListBox的ItemTemplate又是一个GridTemplate,它是一个网格。列表框中列表框的布局似乎工作正常。但是,我的数据绑定存在问题。
对于第二层列表框ItemsSource,我尝试使用Collection Current Item Bindings ItemSource="{Binding /}"
并使用ItemsSource="{TemplateBinding /}"
进行绑定。我是WPF的新手,并且正在使用MVVM,所以任何提示和/或批评都会受到赞赏。
<ListBox Grid.Row="4" Width="610" Height="600" HorizontalContentAlignment="Stretch" ItemsSource="{Binding CurrentLocation.Children}">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBox Width="550" Height="100" Margin="5" HorizontalContentAlignment="Stretch" ItemsSource="{Binding /}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Margin="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="3*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<TextBlock Grid.Column="0" Grid.Row="0" Margin="5" Text="Name:" />
<TextBlock Grid.Column="0" Grid.Row="1" Margin="5" Text="Description:" />
<TextBlock Grid.Column="1" Grid.Row="0" Margin="5" Text="{Binding Name}" />
<TextBlock Grid.Column="1" Grid.Row="1" Margin="5" Text="{Binding Description}" TextWrapping="Wrap" />
<Button Grid.Column="2" Grid.Row="0" Command="{Binding TODO}">
<TextBlock Text="Edit"/>
</Button>
<Button Grid.Column="2" Grid.Row="1" Command="{Binding TODO}">
<TextBlock Text="Delete"/>
</Button>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 0 :(得分:1)
作为整体绑定到当前DataContext
的正确表示法是{Binding}
。
<ListBox ... ItemsSource="{Binding CurrentLocation.Children}">
<ListBox.ItemTemplate>
<DataTemplate>
<ListBox ... ItemsSource="{Binding}" >
<ListBox.ItemTemplate>
<DataTemplate>
<Grid HorizontalAlignment="Stretch" Margin="5">
<!-- snip -->
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
答案 1 :(得分:1)
每个ListBoxItem
都包含父集合中对象的DataContext
,因此您可以在Binding中指定任何内容。
<ListBox ItemsSource="{Binding MyCollectionOfCollections}">
<ListBox.ItemTemplate>
<DataTemplate>
<!-- DataContext of each item will an inner ObservableCollection<Location> -->
<ListBox ItemsSource="{Binding }" />
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>