CompositeCollection + CollectionContainer: Bind CollectionContainer.Collection to property of ViewModel that is used as DataTemplates DataType

时光怂恿深爱的人放手 提交于 2019-11-27 14:04:49
Oliver

Due to the issue with data binding on CollectionContainer as described http://social.msdn.microsoft.com/Forums/vstudio/en-US/b15cbd9d-95aa-47c6-8068-7ae9f7dca88a/collectioncontainer-does-not-support-relativesource?forum=wpf I now use the following approach:

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

Edit: The CompositeCollection class does not derive from FrameworkElement and thus does not have a DataContext property to support data binding. It will only work if you use Binding providing a Source. Have a look here https://stackoverflow.com/a/6446923/1254795 for more information.

Try giving name to your ListBox and refer its DataContext in binding:

   <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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!