Monday, May 16, 2011

WPF - Image Gallery in WPF

In this article i will show you how to create a Dynamic Image Gallery in WPF application by using Listbox and UniformGrid Panel.

Step 1
Create a WPF Application and give solution name as WpfImageGallery.

Step 2
Create a New Folder in the Solution and give folder name as Images,it is look like this



Click on Image for Better View

Step 3
Create a XML file in Application BaseDirectory and give file name as ImageData.xml.(./bin/debug/ImageData.xml)

Step 4
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called
ImageName.,it is look like this






<?xml version="1.0" encoding="utf-8" ?>
<Images>

<Image>
    <ImagePath>../Images/Gaara.png</ImagePath>
  </Image>

  <Image>
    <ImagePath>../Images/Choji.png</ImagePath>
  </Image>

  <Image>
    <ImagePath>../Images/Jiraiya.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>../Images/Kakashi.png</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/Kiba.png</ImagePath>
  </Image>
<Image>
    <ImagePath>../Images/Naruto.jpg</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/Neji.jpg</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/RockLee.jpg</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/Sai.jpg</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/Shikamaru.jpg</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/Shino.jpg</ImagePath>
  </Image>

<Image>
    <ImagePath>../Images/Yamato.jpg</ImagePath>
  </Image>

</Images>

Step 5
Create a ImageEntity Class in the solution.it is an Entity class,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WpfImageGallery
{
    public class ImageEntity
    {
        #region Property

      
        public String ImagePath
        {
            get;
            set;
        }

        #endregion
    }
}
Step 6
Create a ImageView Static Class in a solution for retriving Image Path from XML Document,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace WpfImageGallery
{
    public static class ImageView
    {
        #region Methods

        public static List<ImageEntity> GetAllImagesData()
        {
            try
            {
                // Load Xml Document
                XDocument XDoc = XDocument.Load("ImageData.xml");

                // Query for retriving all Images data from XML
                var Query = from Q in XDoc.Descendants("Image")
                            select new ImageEntity
                            {
                                ImagePath = Q.Element("ImagePath").Value
                            };

                // return images data
                return Query.ToList<ImageEntity>();

            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

        #endregion
    }
}

Step 7
Now design Image gallery on window.Drag and drop ListBox Control from Toolbox and
set a Background Color,it is look like this

<ListBox x:Name="LsImageGallery">
            <ListBox.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black"/>
                    <GradientStop Color="#FF1E2A2F" Offset="1"/>
                </LinearGradientBrush>
            </ListBox.Background>
        </ListBox>





Step 8
Create a DataTemplate and ItemPanelTemplate to a Listbox control,it is look like this
<Window.Resources>

        
        <DataTemplate x:Key="ImageGalleryDataTemplate">
            <Grid>
                <Border BorderBrush="#FFFF9800" BorderThickness="3"  Width="120" Height="120" Padding="10" Margin="15" CornerRadius="10">
                    <!--Bind Image Path in Image Control-->
                    <Image Source="{Binding ImagePath}" Stretch="Fill"  HorizontalAlignment="Center">
                            <!--View Large Image on Image Control Tooltip-->
                            <Image.ToolTip>
                                <Grid>
                                    <Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200"></Image>
                                </Grid>    
                            </Image.ToolTip>                
                            
                    </Image>

                </Border>
            </Grid>
        </DataTemplate>
        
        <ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
            
            <!--Display Images on UniformGrid Panel-->
            <UniformGrid Columns="4" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
            
        </ItemsPanelTemplate>

        
    </Window.Resources>

Step 9
Apply DataTemplate and ItemPanelTemplate on ListBox Control,it is look like this

<ListBox x:Name="LsImageGallery"  ItemsSource="{Binding}" ItemTemplate="{DynamicResource ImageGalleryDataTemplate}" ItemsPanel="{DynamicResource ImageGalleryItemsPanelTemplate}">
            <ListBox.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black"/>
                    <GradientStop Color="#FF1E2A2F" Offset="1"/>
                </LinearGradientBrush>
            </ListBox.Background>
        </ListBox>


ItemSource Property - Gets or sets a collection used to generate the content of the ItemsControl.

ItemTemplate Property - Gets or sets the DataTemplate used to display each item.

ItemPanel PropertyGets or sets the template that defines the panel that controls the layout of items.

Step 10
Now Bind the data in ListBox Control in Code Behind,it is look like this

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfImageGallery
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();

            try
            {
                BindImages(); // Bind Image in Constructor
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        /// <summary>
        /// Bind Image in List Box Control
        /// </summary>
        private void BindImages()
        {
            try
            {
                // Store Data in List Object
                List<ImageEntity> ListImageObj = ImageView.GetAllImagesData();

                // Check List Object Count
                if (ListImageObj.Count > 0)
                {
                    // Bind Data in List Box Control.
                    LsImageGallery.DataContext = ListImageObj;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}

Run The Project.

Output



















Move the Mouse Pointer to the Image





















Full XAML Code

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"
    x:Class="WpfImageGallery.MainWindow"
    x:Name="Window"
    Title="Image Gallery"
    Width="640" Height="500">
    
    <Window.Resources>

        
        <DataTemplate x:Key="ImageGalleryDataTemplate">
            <Grid>
                <Border BorderBrush="#FFFF9800" BorderThickness="3"  Width="120" Height="120" Padding="10" Margin="15" CornerRadius="10">
                    <!--Bind Image Path in Image Control-->
                    <Image Source="{Binding ImagePath}" Stretch="Fill"  HorizontalAlignment="Center">
                            <!--View Large Image on Image Control Tooltip-->
                            <Image.ToolTip>
                                <Grid>
                                    <Image Source="{Binding ImagePath}" Stretch="Fill" HorizontalAlignment="Center" Height="200" Width="200"></Image>
                                </Grid>    
                            </Image.ToolTip>                
                            
                    </Image>

                </Border>
            </Grid>
        </DataTemplate>
        
        <ItemsPanelTemplate x:Key="ImageGalleryItemsPanelTemplate">
            
            <!--Display Images on UniformGrid Panel-->
            <UniformGrid Columns="4" HorizontalAlignment="Center" VerticalAlignment="Stretch"/>
            
        </ItemsPanelTemplate>

        
    </Window.Resources>

    <Grid x:Name="LayoutRoot">
        
        <ListBox x:Name="LsImageGallery"  ItemsSource="{Binding}" ItemTemplate="{DynamicResource ImageGalleryDataTemplate}" ItemsPanel="{DynamicResource ImageGalleryItemsPanelTemplate}">
            <ListBox.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black"/>
                    <GradientStop Color="#FF1E2A2F" Offset="1"/>
                </LinearGradientBrush>
            </ListBox.Background>
        </ListBox>
        
    </Grid>
</Window>


Download
Download Source Code 

I had created another Image Gallery.Please Check it.I hope you Like it.
Download Source Code from the following Link
 
Downalod Source Code - ImageGallery_2

Output



 

30 comments:

  1. Thank you very much for this great example. Too many WPF samples are unnecessarily complex and I enjoyed your simple, straightforward example.

    ReplyDelete
  2. Nice Article..

    Thanks,
    MOhan

    ReplyDelete
  3. Replies
    1. Thanks dogan.

      i hope you like my article......

      Delete
  4. it is very good...thanks.
    how can i make a image gallery for those images which are saved in the database(sql server 2008),can u tell me??pls..

    ReplyDelete
  5. Sorry For Late Reply.

    Yes I can Help you.

    Can you send your email ID???

    ReplyDelete
  6. Thanks for this good article.
    Is it possible to display a label under each image?

    ReplyDelete
    Replies
    1. Yes. you can add a lable control below the Image control in Data Template.

      Delete
  7. Please, how can i add button to this application ???

    ReplyDelete
  8. Great article, i wanna use this in my application. But am having a lil question, how will i implement paging in this application. Suppose i have 1000 images in my application. How will i implement it?

    ReplyDelete
    Replies
    1. Suppose i like to have 10 images in the page, and i wanna display only 30 images at a time.. and i want to create a scrollbar using which i can go to the appropriate page.. If i happen to go to that page, I shud load only images at that page.. how will i do that?

      Delete
  9. hello,
    i used this example in my app and it's very simple and easy to implement.
    The only problem I have is that some jpg doesn't display. Is there some issue about this ? Thanks, Adrian

    ReplyDelete
    Replies
    1. Can you send your solution copy on my mail id???

      kishor.naik011.net@gmail.com

      Delete
  10. Hi Kishore,

    i used this example in my app. I am loading the image from database.Everything is working fine. When an image is clicked i have to get the image id and based on that id i have to process some data.I created a label to bind the imageid like this
    "Label Name="lblColorID" Content="{Binding ColorID}" " and thought of fetching the id in selection change event of listbox. But i am getting the error "The name 'lblImageID' does not exist in the current context". Can you pls help me in this....

    ReplyDelete
    Replies
    1. Could you send your Solution Copy on my mail ID????

      kishor.naik011.net@gmail.com

      Delete
  11. Damn it, that roxx!! Seriously, thank you for that demonstration.
    Please, keep going like that!

    ReplyDelete
    Replies
    1. But, I have a request:
      Could you increase the width of you text, because your code text doesn't show as well(I'm using Chrome).
      Thanks ;)

      Delete
  12. Really nice article. Saved my lots of time.

    Thank you for this wonderful post.

    ReplyDelete
  13. Nice Article.

    Please let me know how we can display the Tooltip dynamically on these images by extracting only name of the image from imagePath.



    ReplyDelete
  14. Tanks for good Explanation. I am a new with WPF. I will Select multiples images programmaticly (As result on an Algorithem) the selected images should have Border with Green Color and not selected with Red. hwo can I do this?
    selection per maus or keybord should be disabled ?

    ReplyDelete
  15. I need to browse d image n save those images in a database n display those images in a carousel... Help me out.... nithin3324@gmail.com is my mail id

    ReplyDelete
  16. I need to browse d image n save those images in a database n display those images in a carousel... Help me out.... nithin3324@gmail.com is my mail id

    ReplyDelete
  17. Update the first link, please.
    tkx

    ReplyDelete