How do I add multiple images in StackPanel WPF fro

2019-01-15 17:25发布

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条回答
虎瘦雄心在
2楼-- · 2019-01-15 18:06

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>
查看更多
登录 后发表回答