在DataTemplate中绑定CollectionViewSource [英] Binding a CollectionViewSource within a DataTemplate

查看:57
本文介绍了在DataTemplate中绑定CollectionViewSource的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ContentTemplate是一个数据模板,它显示一个具有成员 FooList(一个ObservableCollection)的对象。

'ContentTemplate' is a DataTemplate that displays an object which has a member 'FooList' (an ObservableCollection).

<DataTemplate x:Key="ContentTemplate">
    <ListBox ItemsSource="{Binding Path=FOO}">
        ...
    </ListBox>
</DataTemplate>

我需要能够使用CollectionViewSource过滤该FooList。通常这很简单,但是我似乎无法在DataTemplate中使用绑定。我尝试这样做:

I need to be able to filter that FooList using a CollectionViewSource. This is usually been straight forward but I can't seem to get the binding to work within a DataTemplate. I attempted to this:

<DataTemplate x:Key="ContentTemplate">
    <DataTemplate.Resources>
        <CollectionViewSource x:Key="CVS" Source="{Binding Path=FooList}" Filter="FooFilter"/>
    <DataTemplate.Resources>
    <ListBox ItemsSource="{Binding Source={StaticResource CVS}}">

我从中得到的错误是:

System.Windows.Data错误:2:找不到目标元素的管理FrameworkElement或FrameworkContentElement。 BindingExpression:Path = FooList; DataItem = null;目标元素是 CollectionViewSource(HashCode = 52991666); target属性是 Source(类型 Object)

在我看来,这就像是在CollectionViewSource上查找 FooList而不是绑定对象

Which sounds to me like it's looking for 'FooList' on the CollectionViewSource instead of the object bound to the DataTemplate.

所以...如何让它查看正确的对象?

So... how do I get this to look at the correct object?

推荐答案

据我了解,DataTemplate充当有关将哪些内容插入可视化树的指令,但并未成为可视化树本身的一部分。在遇到与上述问题相同的问题后,我才得出这个假设。我通过将CollectionViewSource附加到元素的资源来解决此问题,该元素将是可视树的一部分,在我的例子中是网格。这是起作用的示例:

As I understand it, the DataTemplate acts as instructions on what to insert into the visual tree but does not become a part of the visual tree itself. I only came to this hypothesis after running into the same problem you've described above. I fixed the issue by attaching the CollectionViewSource to the resources of an element that would be part of the visual tree, in my case a grid. Here is the sample that did work:

<DataTemplate DataType="{x:Type TypedLists:AssetModelListViewModel}">
    <Grid>
        <Grid.Resources>
            <CollectionViewSource x:Key="items"
                                  Source="{Binding}">
                <CollectionViewSource.SortDescriptions>
                    <scm:SortDescription PropertyName="AssetType.AssetCategory.Name" />
                    <scm:SortDescription PropertyName="AssetType.Name" />
                    <scm:SortDescription PropertyName="Manufacturer.Name" />
                </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
        </Grid.Resources>

        <ListView ItemsSource="{Binding Source={StaticResource items}}">

        </ListView>
    </Grid>
</DataTemplate>

这篇关于在DataTemplate中绑定CollectionViewSource的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆