WPF Image Viewer Part 6, Binding to Current List Item

This is a part of the WPF image viewer tutorial: Introduction, Part 1, Part2, Part 3, Part 4 and Part 5.

In this post were going to replace the big blue area in the center of our window with an image, obviously the image we want is the selected thumbnail from the list box to the left.

First let's replace the blue rectangle with an image control, then we'll figure out how to get the image into it, just replace the second rectangle in the XAML file with an <Image/> element.

Now let's play with data binding, WPF has very nice support for binding to the current item, just two tiny changes to our XAML:

  • Add IsSynchronizedWithCurrentItem="True" to the list box
  • Add Source="{Binding AllImages/Image}" to the image

Were done, you can now run the program - and see it doesn't work at all, the reason is in our C# code, the AllImages property creates a new list every time it runs, so the list the list box gets and the list the image gets are not the same list – and two different lists have two different current items.

It's easy to fix the C# code to make it work, but let's pretend we are trying to work around a bug in a data source we can't fix, wouldn't it be nice if we could grab the image directly from the list box? Fortunately it's easy to do:

First, set a name for the list box, add Name="ImageList" to the list box element

Now use the name to reference the list box in a binding expression, change the image's source property to:

Source="{Binding ElementName=ImageList,Path=SelectedItem.Image}"

You can see we can get the value from any control in our window by using the Binding's ElementName property and that WPF has no problem with the Image property not being a property of the list box (this is why it's named Path and not something like PropertyName).

One last thing before finishing this post, since we ended up not using the current item support you can remove the IsSynchronizedWithCurrentItem="True" from the list box.

In the next post we'll add the ability to rotate the image.

posted @ Tuesday, September 18, 2007 11:26 AM

Comments on this entry:

# re: WPF Image Viewer Part 6, Binding to Current List Item

Left by Kai at 1/30/2008 3:58 AM

Does the "next post" exist somewhere?

# re: WPF Image Viewer Part 6, Binding to Current List Item

Left by Nir Dobovizki at 1/30/2008 8:30 AM

I forgot to link to the next post, it's fixed now.

# re: WPF Image Viewer Part 6, Binding to Current List Item

Left by Vlad at 3/20/2008 5:30 PM

I had been struggling with why my ListBox wasn't in sync with my ListCollectionView for an hour or so until I found your post.

Thank you.

# re: WPF Image Viewer Part 6, Binding to Current List Item

Left by Maj3d at 3/18/2009 3:26 PM

Its taking to long to load, is there a more efficient way of doing this, such as reducing image size b4 adding to list?

Your comment:



 (will not be displayed)


 
 
 
Please add 5 and 6 and type the answer here: