Jeff Patterson
Jeff Patterson

Reputation: 44

WPF image collection to ListView without using a file path

I am working on a vision application and have a camera(s) that takes pictures and stores them in a collection as bitmaps.

Is there a way to add the bitmap images to a listview without a file path in the source?

I can already write the images to disk and then display them in a ListView. The trouble with that method is the quantity of images. The machine will take 3 pictures every second while it is running 24/7. I suspect that I will destroy the SSD in a short time.

So I would like to find a better way. I don't have to use a listView and all of the examples I have seen thus far are all various flavors of using a disk file path. If there is a better collection to use I will gladly change.

Thanks for your advice.

I could not get this to work: https://learn.microsoft.com/en-us/dotnet/api/system.windows.media.imaging.bitmapsource?redirectedfrom=MSDN&view=netcore-3.1 I thought is was the most promising. But I am using System.Drawing.Imaging.

Upvotes: 1

Views: 543

Answers (1)

Clemens
Clemens

Reputation: 128061

Your view model should expose a collection property that has ImageSource or BitmapSource as element type:

For the conversion from Sytem.Drawing.Bitmap to BitmapSource, see e.g. this question: fast converting Bitmap to BitmapSource wpf, or this: Load a WPF BitmapImage from a System.Drawing.Bitmap

public class ViewModel
{
    public ObservableCollection<BitmapSource> Images { get; }
        = new ObservableCollection<BitmapSource>();

    public void AddImage(System.Drawing.Bitmap bitmap)
    {
        Images.Add(Convert(bitmap));
    }

    public static BitmapSource Convert(System.Drawing.Bitmap bitmap)
    {
        ...
    }
}

Assign an instance of the view model to the DataContext of the view, and populate the collection:

public partial class MainWindow : Window
{
    private readonly ViewModel viewModel = new ViewModel();

    public MainWindow()
    {
        InitializeComponent();
        DataContext = viewModel;
    }
}

Bind a ListBox like this:

<ListBox ItemsSource="{Binding Images}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding}"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Upvotes: 2

Related Questions