views:

1096

answers:

1

I currently have a collection with a HasChanges property on it (each object in the collection also has its own HasChanges property) and the collection is the source of my CollectionViewSource.

When I try to databind the HasChanges property of the collection behind the CollectionViewSource to one of my custom controls, it binds to the HasChanges property of the currently selected object, instead of HasChanges property of the CollectionViewSource's source collection. Is there a way that I can explicitly tell the binding to look on the collection object rather than the objects in the collection?

My code looks something like this:

<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>

Thanks.

+2  A: 

When you bind to CollectionViewSource you get a CollectionView, which has a SourceCollection property that you can use to get the collection behind the CollectionViewSource, like so:

<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>
Robert Macnee