0

I'm using a simple WPF-App (.NET Framework) with Xaml and CodeBehind. In the XAML I defined a Listbox, which is filled by the code behind.

The problem: When I click on the button, the respective image should be deleted. But this is not possible, because the image is used by the process. So how can I close the image? Or how to open it with a streamreader?

The problem is, that the images are shown in a Listbox, so I can't reach the image. If I click the button, I reach the parent FrameworkElement, but not the childs of the parent, where the image is.

Thank you!

XAML:

<Grid>
    <ListBox Name="ImagesListBox">
        <ListBox.ItemTemplate >
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <Image Source="{Binding FilePath}" Height="50"/>
                    <Button Content="DeleteImage" Click="Button_Click"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Grid>

CodeBehind:

public partial class MainWindow : Window
{
    public class OwnImage
    {
        public string FilePath { get; set; }
    }

    List<OwnImage> ImageList;

    public MainWindow()
    {
        InitializeComponent();
        ImageList = new List<OwnImage>
        {
            new OwnImage() { FilePath = "D:\\Temp\\bg.jpg" },
            new OwnImage() { FilePath = "D:\\Temp\\WinA.jpg" }
        };

        ImagesListBox.ItemsSource = ImageList;
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        FrameworkElement baseobj = sender as FrameworkElement;
        OwnImage image = baseobj.DataContext as OwnImage;

        // How to delete the image file?
    }
}
trophi20
  • 1
  • 2
  • See the answers to the duplicate question. Use a Binding Converter to create a BitmapImage from a file path. For notifying the Ui on removing elements from the ItemsSource collection, use an ObservableCollection. – Clemens Jun 06 '21 at 07:37

0 Answers0