1

I want to give folder path and from that folder path If That folder contains 3 images I want to display those 3 images into StackPanel WPF Form

I tried something like below which works fine for one image but how can load all the images from given folder?

<Window x:Class="wpfBug.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
    <StackPanel Name="sp">
    </StackPanel>
</Window>



private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Image i = new Image();
            BitmapImage src = new BitmapImage();
            src.BeginInit();
            src.UriSource = new Uri("mypic.png", UriKind.Relative);
            // how to load all images from given folder?
            src.EndInit();
            i.Source = src;
            i.Stretch = Stretch.Uniform;
            //int q = src.PixelHeight;        // Image loads here
            sp.Children.Add(i);
        }

1 Answer 1

3

You should use an ItemsControl like shown below. It uses a vertical StackPanel as default panel for its items.

<ItemsControl x:Name="imageItems">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}" Margin="5"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Set the ItemsSource of the ItemsControl like this:

imageItems.ItemsSource = Directory.EnumerateFiles(FOLDERPATH, "*.png");

The conversion from path string to ImageSource is performed by built-in type conversion in WPF.


You may use a different ItemsPanel like this:

<ItemsControl ...>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    ...
</ItemsControl>
Sign up to request clarification or add additional context in comments.

8 Comments

I think all images are loasing on each other :( how can I make a space in between two images ?
Set their Margin property.
still only one image is displayed :O strange I have written imageItems.ItemsSource = Directory.EnumerateFiles(FOLDERPATH, "*.png"); on Window_Loaded
Not sure what you mean. If you set the size of the ItemsControl you should make sure that the Images can fit into its size. You may give the Image controls an appropriate (smaller) size. Or put the ItemsControl in a ScrollViewer.
Replace ItemsSource by ListBox. It has a vertical ScrollBar by default. If it also shows only one image, then there is only one (png) in your folder.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.