且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-25 20:54:00

您应该使用如下所示的 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>