如何从文件夹在 StackPanel WPF 中添加多个图像? [英] How do I add multiple images in StackPanel WPF from Folder?

查看:40
本文介绍了如何从文件夹在 StackPanel WPF 中添加多个图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想给文件夹路径和从那个文件夹路径如果那个文件夹包含3张图片我想显示这3张图片到<代码>StackPanel WPF 表单

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);
        }

推荐答案

您应该使用如下所示的 ItemsControl.它使用垂直 StackPanel 作为其项目的默认面板.

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>

像这样设置ItemsControl的ItemsSource:

Set the ItemsSource of the ItemsControl like this:

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

路径字符串到ImageSource的转换是通过WPF内置的类型转换来完成的.

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

您可以像这样使用不同的 ItemsPanel:

You may use a different ItemsPanel like this:

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

这篇关于如何从文件夹在 StackPanel WPF 中添加多个图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆