Martijn's blog - E-Commerce, EAI, BizTalk and .NET

2006/10/17

WPF - Using CompositeCollection to combine multiple sources for databinding

As I said before, I'll blog about things I learn and find interesting... ;-) Today, I realized there's a very easy way to combine different sources for a binding. It's done using what's called a CompositeCollection. Here's how it works:
  1. Create a datasource (XmlDataProvider, ObjectDataProvider, ...)
  2. Create a CollectionViewSource to look at the data in a specific way
  3. Bind a control's Source/ItemsSource/... property to the CollectionViewSource
  4. Add a view 'static' items
  5. Bind to another view at the same or different data
An example:
<XmlDataProvider x:Key="MyData" XPath="/Info">
  <x:XData>
    <Info xmlns="">
      <Item ID="12345" Name="Book 1" Price="$10.00" />
      <Item ID="24678" Name="Book 3" Price="$9.00" />
    </Info>
  </x:XData>
</XmlDataProvider>

<CollectionViewSource x:Key='a' Source="{Binding Source={StaticResource MyData}, XPath=Item/@Price}" />
<CollectionViewSource x:Key='b' Source="{Binding Source={StaticResource MyData}, XPath=Item/@Name}" />

We now have the two CollectionViewSource instances up and running. For example purposes, they're looking at the same datasource, but this could be anything else. Now, let's create a simple ListBox control which binds to both these CollectionViewSource instances and adds constant items..
<ListBox>
  <ListBox.ItemsSource>
    <Binding>
      <Binding.Source>
        <CompositeCollection>
          <ListBoxItem>My Constant Item</ListBoxItem>
          <CollectionContainer Collection="{Binding Source={StaticResource a}}" />
          <CollectionContainer Collection="{Binding Source={StaticResource b}}" />
        </CompositeCollection>
      </Binding.Source>
    </Binding>
  </ListBox.ItemsSource>
</ListBox>

It's as easy as that. The output would be:

My Constant Item
$10.00
$9.00
Book 1
Book 3

Just like the MergedDictionaries within the ResourceDictionary, you can easily combine different sources of data and bind to those sources, even TwoWay.

12 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home