我没有获得正确的Binding语法来访问Cats
中Dogs
的{{1}}和MyViewModel
属性,这些属性在其资源中定义了DateTemplate
CompositeCollection
public class MyViewModel
{
public ObservableCollection<Cat> Cats { get; private set; }
public ObservableCollection<Dog> Dogs { get; private set; }
}
我需要为????插入什么?将<DataTemplate DataType={x:Type local:MyViewModel}">
<DataTemplate.Resources>
<CompositeCollection x:Key="MyColl">
<!-- How can I reference the Cats and Dogs properties of MyViewModel? -->
<CollectionContainer Collection="{Binding Dogs, ????}">
<CollectionContainer Collection="{Binding Cats, ????}">
</CompositeCollection>
</DataTemplate.Resources>
<ListBox ItemsSource="{StaticResource MyColl}">
<!-- ... -->
</ListBox>
</DataTemplate>
和Dogs
集合绑定到Cats
s?
答案 0 :(得分:38)
由于CollectionContainer
上的数据绑定问题如http://social.msdn.microsoft.com/Forums/vstudio/en-US/b15cbd9d-95aa-47c6-8068-7ae9f7dca88a/collectioncontainer-does-not-support-relativesource?forum=wpf所述,我现在使用以下方法:
<ListBox>
<ListBox.Resources>
<CollectionViewSource x:Key="DogCollection" Source="{Binding Dogs}"/>
<CollectionViewSource x:Key="CatCollection" Source="{Binding Cats}"/>
</ListBox.Resources>
<ListBox.ItemsSource>
<CompositeCollection>
<CollectionContainer Collection="{Binding Source={StaticResource DogCollection}}"/>
<CollectionContainer Collection="{Binding Source={StaticResource CatCollection}}"/>
</CompositeCollection>
</ListBox.ItemsSource>
<!-- ... -->
</ListBox>
编辑: CompositeCollection
类不是从FrameworkElement
派生的,因此没有DataContext
属性来支持数据绑定。它仅在您使用Binding
提供Source
时才有效。有关详细信息,请查看https://stackoverflow.com/a/6446923/1254795。
答案 1 :(得分:4)
尝试为ListBox提供名称,并在绑定中引用其DataContext:
<ListBox x:Name="myList" ItemsSource="{DynamicResource MyColl}">
<ListBox.Resources>
<CompositeCollection x:Key="MyColl">
<CollectionContainer Collection="{Binding DataContext.Dogs, Source={x:Reference myList}}"/>
<CollectionContainer Collection="{Binding DataContext.Cats, Source={x:Reference myList}}"/>
</CompositeCollection>
</ListBox.Resources>
</ListBox>