Home > View Post

How binding to the Current Item works

In a previous post Binding to the Current Item in WPF I discussed the capability of WPF to synchronise one or more selectors (ListBox, ComboBox, ListView etc) to a collection.

There was even an example in Xaml that had two selectors (a listbox and a combobox) bound to the same array and were thus kept in sync.

two selectors

The curious reader might have wondered just how this works? Where does this shared state reside such that it can be accessed by both controls? After all, the System.Array type doesn't have any CurrentIndex property!

The answer is both simple and cunning.

All ItemsControls actually bind to a ICollectionView. Since the data I bound to wasn't of type ICollectionView the WPF controls will call CollectionViewSource.GetDefaultView(object source) to get the default view and this will return the same ICollectionView.

Here's an (N)Unit test that proves it:

[Test]
public void TestCollectionViewSource()
{
    int[] array = new int[32];

    ICollectionView view1 = CollectionViewSource.GetDefaultView(array);
    ICollectionView view2 = CollectionViewSource.GetDefaultView(array);

    Assert.IsTrue(Object.ReferenceEquals(view1, view2));
}

Note that I'm not just testing for equality but checking that it returns the exact same Reference to the same object.

Bootiful.

PS - Next post in the 10 reasons coming soon.

Tags: WPF

 
Josh Post By Josh Twist
1:53 PM
13 Nov 2007

» Next Post: Reason 7. The ListView
« Previous Post: Reason 6. Layout

Comments are closed for this post.

© 2005 - 2017 Josh Twist - All Rights Reserved.