WPF中图片的宫格显示

1.解释说明

  • 使用ScrollViewer控件来达到滑动的效果

  • 使用WrapPanel的自动换行特性,保证图片在占满横向空间后自动往下排布

  • 使用foreach的方法来游历所有的图片url

2.xaml代码示例

cs 复制代码
<Grid>
    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <WrapPanel Name="imageWrapPanel" Orientation="Horizontal" Margin="10">
            <!-- 图片将动态添加到这里 -->
        </WrapPanel>
    </ScrollViewer>
</Grid>

3.cs代码示例

cs 复制代码
//加载url转换成BitmapImage
private async Task<BitmapImage> LoadImageFromUrl(string url)
{
    try
    {
        using (HttpClient client = new HttpClient())
        {
            byte[] imageBytes = await client.GetByteArrayAsync(url);
            using (var stream = new System.IO.MemoryStream(imageBytes))
            {
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.StreamSource = stream;
                bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                bitmapImage.EndInit();
                return bitmapImage;
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Error loading image: {ex.Message}");
        return null;
    }
}


//显示图片
private async void LoadImagesFromServer()
{
    // 模拟从服务器获取图片URL列表
    string[] imageUrls = new string[]
    {
       "https://example1.png",
       "https://example2.png",
       "https://example3.png",
        // 添加更多图片URL
    };

    foreach (var imageUrl in imageUrls)
    {
        BitmapImage bitmapImage = await LoadImageFromUrl(imageUrl);
        if (bitmapImage != null)
        {
            Image image = new Image
            {
                Source = bitmapImage,
                Width = 200, // 设置图片宽度
                Height = 200, // 设置图片高度
                Margin = new Thickness(5) // 设置图片间距
            };
            imageWrapPanel.Children.Add(image);
        }
    }
}
相关推荐
三千道应用题5 小时前
WPF&C#超市管理系统(6)订单详情、顾客注册、商品销售排行查询和库存提示、LiveChat报表
开发语言·c#·wpf
✎ ﹏梦醒͜ღ҉繁华落℘1 天前
开发WPF项目时遇到的问题总结
wpf
hqwest2 天前
C#WPF实战出真汁06--【系统设置】--餐桌类型设置
c#·.net·wpf·布局·分页·命令·viewmodel
Vae_Mars2 天前
WPF中使用InputBindings进行快捷键绑定
wpf
hqwest2 天前
C#WPF实战出真汁05--左侧导航
开发语言·c#·wpf·主界面·窗体设计·视图viewmodel
hqwest2 天前
C#WPF实战出真汁01--项目介绍
开发语言·c#·wpf
wuty0073 天前
WPF 实现支持动态调整高度的文本显示控件
wpf·scrollviewer·extentheight·自动高度控件·动态调整高度
范纹杉想快点毕业6 天前
C 语言主控开发与显控开发能力体系及技术栈详解,STM32、QT、嵌入式、边缘系统显示
stm32·单片机·tcp/ip·microsoft·fpga开发·51单片机·wpf
weixin_447103586 天前
WPF之绑定!
c#·wpf
DataIntel6 天前
wpf问题记录
wpf