简体   繁体   English

如何从文件夹在 StackPanel WPF 中添加多个图像?

[英]How do I add multiple images in StackPanel WPF from Folder?

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我想提供folder path和该文件夹路径如果该folder contains 3 images我想display those 3 imagesStackPanel 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);
        }

You should use an ItemsControl like shown below.您应该使用如下所示的ItemsControl It uses a vertical StackPanel as default panel for its items.它使用垂直 StackPanel 作为其项目的默认面板。

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

Set the ItemsSource of the ItemsControl like this:像这样设置 ItemsControl 的ItemsSource

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

The conversion from path string to ImageSource is performed by built-in type conversion in WPF.从路径字符串到ImageSource的转换是通过 WPF 中的内置类型转换来执行的。


You may use a different ItemsPanel like this:您可以像这样使用不同的 ItemsPanel:

<ItemsControl ...>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    ...
</ItemsControl>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM