Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
603 views
in Technique[技术] by (71.8m points)

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

I do not get the correct Binding syntax to access the Cats and Dogs properties of MyViewModel within a DateTemplate that defines a CompositeCollection within 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 have to insert for ???? to bind the Dogs and Cats collections to the CollectionContainers?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...