如何显示ListView中的实际图像而不是其位置?(How to display an actual image in ListView rather than its location?)

编程入门 行业动态 更新时间:2024-10-17 12:23:01
如何显示ListView中的实际图像而不是其位置?(How to display an actual image in ListView rather than its location?)

我发现这个代码添加图片到WPF中的ListView。 但它只显示图像位置而不是实际图像:

var image = new BitmapImage(); string fileName = @"C:\Peak Sourcing\Work\ppt_test\slides_png\slide1.png"; using (var stream = new FileStream(fileName, FileMode.Open)) { image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream; image.EndInit(); } ListBoxItem item = new ListBoxItem(); Thumbnails.Items.Add(image);

后面的XAML很简单:

<ListView Name="Thumbnails" Margin="10,10,804,10" > <ListView.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="1"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView>

我还发现了其他一些代码,但它们都只是将图像位置显示为字符串而不是图像。 你能帮我解决这个问题吗?

I have found this code to add picture to a ListView in WPF. However it only displays the image location rather than the actual image:

var image = new BitmapImage(); string fileName = @"C:\Peak Sourcing\Work\ppt_test\slides_png\slide1.png"; using (var stream = new FileStream(fileName, FileMode.Open)) { image.BeginInit(); image.CacheOption = BitmapCacheOption.OnLoad; image.StreamSource = stream; image.EndInit(); } ListBoxItem item = new ListBoxItem(); Thumbnails.Items.Add(image);

The XAML behind is simply:

<ListView Name="Thumbnails" Margin="10,10,804,10" > <ListView.ItemsPanel> <ItemsPanelTemplate> <UniformGrid Columns="1"/> </ItemsPanelTemplate> </ListView.ItemsPanel> </ListView>

I also found few other codes, but all of them just show the image location as string rather than image. Can you please help me solve this?

最满意答案

您将BitmapImage添加为ListViewItem ,它不是可见的(因此不会呈现),并显示为ToString() 。

通常情况下,您应该在这种情况下使用DataTemplates ,但这也适用于您:

var fileName = @"C:\Peak Sourcing\Work\ppt_test\slides_png\slide1.png"; var bitmap = new BitmapImage(new Uri(fileName)) { /*.. more bitmap image options if you like .. */ }; var image = new Image() { Source = bitmap /*.. more image options ..*/ } Thumbnails.Items.Add(image);

You are adding BitmapImage as ListViewItem, which is not visual (so it doesn't renders) and displayed as ToString().

Normally you should use DataTemplates in such cases, but this should works for you too:

var fileName = @"C:\Peak Sourcing\Work\ppt_test\slides_png\slide1.png"; var bitmap = new BitmapImage(new Uri(fileName)) { /*.. more bitmap image options if you like .. */ }; var image = new Image() { Source = bitmap /*.. more image options ..*/ } Thumbnails.Items.Add(image);

更多推荐

本文发布于:2023-08-06 13:54:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1450292.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不是   图像   位置   ListView   location

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!