Retrieving Item Image from DB

2 posts, 0 answers
  1. Flippie
    Flippie avatar
    8 posts
    Member since:
    Jan 2008

    Posted 03 Nov 2011 Link to this post

    Dear Telerik,

    I have a database table containing not only the text details of each node but also the Images that should be used for the item Image.
    These image is stored in a binary datafield inside MS SQL.

    Today I am able to populate the treeview items/nodes via binding in XAML but not sure how to bind the item images.

    Find below the XAML with the current binding to populate the treeview:

    <

    sdk:HierarchicalDataTemplate ItemsSource="{Binding Nodes}">

         <TextBlock Text="{Binding Path=Node.Value}"/>

     </sdk:HierarchicalDataTemplate>

     


    Can you please give me some guidance as to how I can bind the Item Image in XAML as well.
    Assuming the Property containing the bitmap is called: Node.Image

    Regards,
    Flippie

  2. Petar Mladenov
    Admin
    Petar Mladenov avatar
    2891 posts

    Posted 08 Nov 2011 Link to this post

    Hi Flippie,

     You can use Image in the template and bind its Source property to the binary data from your DB:

    <DataTemplate x:Key="EmployeeTemplate">
                  <StackPanel Orientation="Horizontal">
                      <Image Source="{Binding Path=Photo, Converter={StaticResource ImageConverter}}" />
                      <TextBlock Text="{Binding LastName}" />
                  </StackPanel>
              </DataTemplate>
    The key moment here is to convert the Byte array into BitmApImage, for example like so:
    public class ImageConverter : IValueConverter
       {
           public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
           {
               using (MemoryStream stream = new MemoryStream(value as Byte[]))
               {
                   stream.Write(value as Byte[], 0, (value as Byte[]).Length);
                   BitmapImage img = new BitmapImage();
                   img.SetSource(stream);
                   return img;
               }
           }
     
           object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
           {
               throw new NotImplementedException();
           }
       }
    You can find a working sample project in this forum thread. Please let us know if it helps you.
    All the best,
    Petar Mladenov
    the Telerik team

    Explore the entire Telerik portfolio by downloading the Ultimate Collection trial package. Get it now >>

  3. DevCraft banner
Back to Top