CompositeCollection + CollectionContainer:将CollectionContainer.Collection绑定到ViewModel的属性,该属性用作DataTemplates DataType

时间:2013-10-08 08:49:03

标签: c# wpf data-binding datatemplate compositecollection

我没有获得正确的Binding语法来访问CatsDogs的{​​{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?

2 个答案:

答案 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>