CompositeCollection + CollectionContainer: Bind CollectionContainer.Collection for the ViewModel property, which is used as a DataTemplates DataType

I am not getting the correct Binding syntax for accessing the Cats and Dogs MyViewModel within a DateTemplate that defines a CompositeCollection in its resources.

 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> 

What do I need to insert for ???? to link Dogs and Cats collections to CollectionContainer s?

+11
c # data-binding wpf datatemplate
Oct 08
source share
2 answers

Due to a problem with data binding to CollectionContainer as described http://social.msdn.microsoft.com/Forums/vstudio/en-US/b15cbd9d-95aa-47c6-8068-7ae9f7dca88a/collectioncontainer-does-not-support- relativesource? forum = wpf Now I 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 is not derived from FrameworkElement and therefore does not have a DataContext to support data binding. It will only work if you use Binding by providing Source . See https://stackoverflow.com/a/296958/ for more information.

+33
Oct 09 '13 at 12:09 on
source share

Try specifying the name in the ListBox and list its DataContext in the 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> 
+4
Oct 08 '13 at 8:57
source share



All Articles