WPF Listbox Binding Images from DB
WPF ListBox control is quite different from windows win forms and it has lots of abilities to extend and design. With just ListBox we can design most of the equivalent controls available in ASP.Net data controls section. However the implementation of WPF ListBox is also quite different from win forms and ASP.Net controls. Due to increase in the sale of Cheap Netbooks Under 200, more and more people are going to use browser based light weight applications that are hosted using a silver light or WPF. So it is better to use WPF, if required it is much easier to convert it to silverlight.For e.g. binding an image is bit tricky than we do in ASP.Net and the linq and Ms SQL Sample DB northwind may demand additional knowledge on the respective technologies
Fetching Database values using Linq to SQL
As it has been already discussed in detail in the article WPF Datagrid and Linq to SQL, I am not going to detail again here. We can use the Linq to SQL to fetch the data and pass it to the WPF to bind the ListBox. The equivalent datatypes will be chose for the respective database fields. So the important mapping we need to note is the Image Datatype in SQL server. This will be mapped as System.Data.Linq.Binary. So when binding this to the Image we need to convert System.Data.Linq.Binary to the expected BitmapSource format.
Converter for Image Source
Since we need to convert the System.Data.Linq.Binary to BitmapSource, we need to specify the converter while assigning the source for the Image in the markup. This can be specified as a StaticResource. Without creating a static resource the markup does not know how to create an instance of the converter class.
Static Resources for the Converter Class
So we need to create a static resource and map the respective class file in the resources section. In the resources section under Window.Resources, we can create the static resource with a reference to the class object. This class object can be specified in the window tag as an attribute xmlns. We can specify our own namespace. In this case I named it as local and targeted to the class ImageConverter.
Image Converter class using the IValueConverter Interface
This converter has to be implementing the IValueConverter. This IValueConverter has the contract to define two methods Convert and ConvertBack. There are some interesting facts to note here in this converter for images. I realized after few hours of struggling that I need to offset 78 bytes for images from Northwind because of the Ole Datatype. The convertback function can be returning null or can throw a not implemented exception
More information and source code an be found at