【问题标题】:How to databind to a property on a collection behind a collectionviewsource?如何将数据绑定到 collectionviewsource 后面的集合上的属性?
【发布时间】:2008-12-15 20:18:34
【问题描述】:

我目前有一个带有 HasChanges 属性的集合(集合中的每个对象也有自己的 HasChanges 属性),并且该集合是我的 CollectionViewSource 的来源。

当我尝试将 CollectionViewSource 后面的集合的 HasChanges 属性数据绑定到我的自定义控件之一时,它会绑定到当前选定对象的 HasChanges 属性,而不是 CollectionViewSource 源集合的 HasChanges 属性。有没有一种方法可以明确告诉绑定查看集合对象而不是集合中的对象?

我的代码如下所示:

<Window x:Class="CollectionEditWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:Local="clr-namespace:My.Local.Namespace;assembly=My.Local.Namespace">
    <Window.Resources>
        <CollectionViewSource x:Name="CVS" x:Key="MyCollectionViewSource" />
    </Window.Resources>

<Local:MyCustomControl HasChanges="{Binding HasChanges, Source={StaticResource 
                         MyCollectionViewSource}}">
<!-- Code to set up the databinding of the custom control to the CollectionViewSource-->
</Local:MyCustomControl>
</Window>

谢谢。

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

    当您绑定到 CollectionViewSource 时,您会得到一个 CollectionView,它有一个 SourceCollection 属性,您可以使用它来获取 CollectionViewSource 后面的集合,如下所示:

    <Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:sys="clr-namespace:System;assembly=mscorlib">
        <Grid.Resources>
            <x:Array x:Key="data" Type="{x:Type sys:String}">
                <sys:String>a</sys:String>
                <sys:String>bb</sys:String>
                <sys:String>ccc</sys:String>
                <sys:String>dddd</sys:String>
            </x:Array>
            <CollectionViewSource x:Key="cvsData" Source="{StaticResource data}"/>
        </Grid.Resources>
        <StackPanel>
            <ListBox ItemsSource="{Binding Source={StaticResource cvsData}}"/>
            <TextBlock Text="{Binding Source={StaticResource cvsData}, Path=Length, StringFormat='{}Length bound to current String = {0}'}"/>
            <TextBlock Text="{Binding Source={StaticResource cvsData}, Path=SourceCollection.Length, StringFormat='{}Length bound to source array = {0}'}"/>
        </StackPanel>
    </Grid>
    

    【讨论】: