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.

4 Comments:

  • ESG Appliance is an appliance repair and service company operating in the Los Angeles and Orange counties and providing Installation, Service and Maintenance for appliances like Ice Maker, Microwave Oven, Washer Dryer

    By Blogger Harry Seo, at 11:26 AM  

  • Thanks for taking this opportunity to discuss this, I feel fervently about this and I like learning about this subject.Sarrell Dental Center

    By Blogger Harry Seo, at 9:12 AM  

  • This Blog is going places, the people, the layout, amazing to see such dedication and focus.

    By Anonymous Gadgets UK, at 9:48 AM  

  • Thanks you. Very good post.Unless they can offer a really compelling reason for users to come back, it will be the next Bebo, MySpace

    By Anonymous Cannon 10755GF, at 11:23 PM  

Post a Comment

<< Home