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

问题描述

我没有正确的绑定语法来访问 DateTemplateMyViewModelCatsDogs 属性> 在其资源中定义一个 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>

我必须插入什么???将 DogsCats 集合绑定到 CollectionContainers?

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

推荐答案

由于 CollectionContainer 上的数据绑定问题,如 http://social.msdn.microsoft.com/Forums/vstudio/en-US/b15cbd9d-95aa-47c6-8068-7ae9f7dca88a/collectioncontainer-does-not-support-relativesource?forum=wpf 我现在使用以下方法:

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 类不是从 FrameworkElement 派生的,因此没有 DataContext 属性来支持数据绑定.它仅在您使用 Binding 提供 Source 时才有效.查看此处https://stackoverflow.com/a/6446923/1254795了解更多信息.

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.

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

09-25 14:21