0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WPFでImageのSourceにパスを指定していたら削除できなかった話

Last updated at Posted at 2020-11-04

TL;DR

  • ListViewでとあるフォルダ内の画像一覧を表示しようとした
  • WPFのImageのSourceにBindingで画像そのもののパスを与えた
  • 表示を終わった時点で使った画像を削除したかったけど、削除できなかった
  • 画像のパスじゃなくて、BitmapImageを与えるようにしたら解決

環境

Windows 10
Visual Studio 2017

最初

MainWindow.xaml
<Image Margin="10,20,10,20" Source="{Binding ImgPath}" />
MainWindowViewModel.cs
public class ThumbnailImage : BindableBase, IThumbnailImage
{
    private string_imgPath;
    public string ImgPath
    {
        get { return this._imgPath; }
        set { SetProperty(ref this._imgPath, value); }
    }

    public ThumbnailImage(string filePath) {
        this.ImgPath = filePath;
    }
}

最終

MainWindow2.xaml
<Image Margin="10,20,10,20" Source="{Binding ImgPath}" />
cs:MainWindowViewModel2.cs
public class ThumbnailImage : BindableBase, IThumbnailImage
{
    private BitmapImage _imgPath;
    public BitmapImage ImgPath
    {
        get { return this._imgPath; }
        set { SetProperty(ref this._imgPath, value); }
    }

    public ThumbnailImage(string filePath) {
        this.ImgPath = CreateBitmapImage(filePath);
    }

    public static BitmapImage CreateBitmapImage(string filePath)
    {
        BitmapImage img = new BitmapImage();
        img.BeginInit();
        img.CacheOption = BitmapCacheOption.OnLoad; // ←ここが重要
        img.UriSource = new System.Uri(filePath);
        img.EndInit();

        return img;
    }
}

CacheOptionBitmapCacheOption.OnLoadにすると、読み込み後に画像ファイルを占有しなくなるそうです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?