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