在列表视图中打开图像时如何删除图像?

How can I delete an image while it is open in listview?

我正在尝试使用此列表视图显示文件夹中的图像

public void LoadData()
{
    var imgList = Directory.GetFiles(directoryPath, "*.jpg", 
    SearchOption.AllDirectories);
    myListView.ItemsSource = imgList;
}

ListView ItemTemplate是一个Image和一个删除Image的按钮 按钮的点击事件处理如下

private void DeleteImg(object sender, RoutedEventArgs e)
{
    string delImg = (string)(sender as Button).DataContext;
    File.Delete(delImg);
    LoadData();
}

当我尝试删除图像时出现以下错误

System.IO.IOException: 'The process cannot access the file 'xyz' because it is being used by another process.'

xyz明明是文件名

我觉得是因为图片是在ListView中打开的 关于如何在删除文件之前关闭文件的任何想法

我尝试过的:

我试过了

myListView.ItemsSource = null;
myListView.Items.Clear();
before delete
also:
System.GC.Collect();
System.GC.WaitForPendingFinalizers();

我找到了这个并且有效;

public void LoadData()
{
var imgList = Directory.GetFiles(directoryPath, "*.jpg", SearchOption.AllDirectories);
myListView.ItemsSource = imgList;
foreach (string f in imgList)
            {

                var bi = new BitmapImage();
                bi.BeginInit();
                bi.CacheOption = BitmapCacheOption.OnLoad;
                bi.UriSource = new Uri(f);
                imgLister.Add(bi);
                bi.EndInit();
                bi.Freeze();
            }
}

Freeze() 方法释放内存,并允许删除文件