We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Here is a problem that one of my colleagues who is just starting to use WPF got himself into. He was working on an application that displays items using an ItemsControl and uses a DataTemplate. Inside the DataTemplate he used an Image. Here is the Xaml code:
This is a much simpler example, but the principal is the same.
Can you see what was he doing wrong?
In the code behind I will create a list and use it as the DataContext:
You will expect to see a window with 4 Images, but this is what you get:
Only one image shows up and all the other templates are empty.
Can you see the problem now?
It took me some time to see it because the code was much more complex, but then I noticed that he used the Image class as a resource for the Image.
Image is a WPF Control and can only have one parent! This is why it only displayed at the last item of the list. This is similar to doing the following:
What would happen here? The following:
I was actually surprised that my friend did not get an Exception, I will definitely have to check why no exception was thrown.
To correct the problem all you have to do is to use Bitmap Image which is a C# Class and not a WPF Control. You should use an Image in the template and use the BitmapImage as its source:
Exactly what we wanted.
If any of you have an idea as to why we did not get an exception I will be happy to hear it.
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd