18

我没有得到正确的 Binding 语法来访问在其资源中定义 a 的a的CatsDogs属性。MyViewModelDateTemplateCompositeCollection

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>

我必须插入什么????将DogsandCats集合绑定到CollectionContainers?

4

2 回答 2

53

由于数据绑定问题,CollectionContainerhttp://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了解更多信息。

于 2013-10-09T12:09:19.697 回答
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>
于 2013-10-08T08:57:48.710 回答