Wednesday, 15 July 2015

Populating images from local storage into WPF application

1. Create new WPF Application.
2. In your main window xaml add 3 grids, your code should looks like this:

<Grid x:Name="MainFrame" ShowGridLines="True">
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        <Grid x:Name="Photo1" Grid.Row="0" Margin="10" Grid.RowSpan="1"/>
        <Grid x:Name="Photo2" Grid.Row="1" Margin="10" Grid.RowSpan="1"/>
        <Grid x:Name="Photo3" Grid.Row="2" Margin="10" Grid.RowSpan="1"/>

3. Open code behind the file and create new function:

private void PutImagesIntoFrame()
            // Get last 3 images saved

            string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "RemotePhoto");

            var directory = new DirectoryInfo(path);

            int numberOfImages = 3;

            List<fileinfo> images = directory.GetFiles("*.jpg").OrderByDescending(m => m.LastWriteTime).Take(numberOfImages).ToList();

            List<imagebrush> imageBrushes = new List<imagebrush>();

            if (images.Count == numberOfImages)
                foreach (FileInfo item in images)
                    ImageBrush imageBrush = new ImageBrush();
                    Image image = new Image();
                    image.Source = new BitmapImage(
                      new Uri(item.FullName));

                    imageBrush.ImageSource = image.Source;


            // Add image brushes to individual grids

            Photo1.Background = imageBrushes[0];
            Photo2.Background = imageBrushes[1];
            Photo3.Background = imageBrushes[2];

4. Add some pictures to My Pictures folder inside RemotePhoto Folder.
5. Your application should looks like this.

No comments:

Post a Comment