我发现这个代码添加图片到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);更多推荐
发布评论