posted on
Thursday, May 08, 2008 12:37 AM |
Filed Under [
WPF
LINQ
]
If you need to store images at DB level, Sql Server varbinary type is what you need to hold your data, which is mapped on Linq Binary type once you import your table to a Linq project. How do you display such an image in a Image WPF control? Obviously you cannot directly bind such a data type to the Image.Source property, unless you define a proper value converter from Binary type to ImageSource type.
That said, if you want to implement one, you need to create a class that implements the IValueConverter interface. For the sake of simplicity, let's suppose that we need to support only one-way binding (Data field to Image.Source); our class might be similar to the one displayed below:
The logic is pretty simple: Linq's Binary type has a method which returns a byte array; what we need to do is only building a MemoryStream from it and use it to build a BitmapImage which is directly bindable to the Image.Source property.
Now, we can store our converter as a resource and use it to perform our XAML binding:
One last note: IValueConverter interface has a ConvertBack method too, which is needed to support two-way binding. In a next post, I'll show you how to create a two-way bindable UserControl with image upload features and we will need to implement the whole IValueConverter interface. For now, it's ok to leave it throwing a NotImplementedException.
Update: Here you will find the missing ConvertBack implementation