本文介绍了CompositeCollection + CollectionContainer:将CollectionContainer.Collection绑定到用作DataTemplates的ViewModel的属性DataType的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我没有获得正确的Binding语法来访问 Cats Dogs 属性 DateTemplate 内的MyViewModel 在资源中定义了一个 CompositeCollection

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>

我必须插入????才能绑定 Dogs Cats 集合到 CollectionContainer s?

What do I have to insert for ???? to bind the Dogs and Cats collections to the CollectionContainers?

推荐答案

对于 CollectionContainer 中的数据绑定的问题,如上所述我现在使用以下方法:

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>

编辑: CompositeCollection class不派生自 FrameworkElement ,因此没有一个 DataContext 属性来支持数据绑定。如果您使用绑定提供,则它将工作。有关详细信息,请查看。

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 http://stackoverflow.com/a/6446923/1254795 for more information.

这篇关于CompositeCollection + CollectionContainer:将CollectionContainer.Collection绑定到用作DataTemplates的ViewModel的属性DataType的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 14:21