简体   繁体   中英

WPF Rectangle FIll imagebrush not updating

I am developing a WPF application, a messenger client. The user should be able to change his avatar image. When he right-clicks his avatar, a open file dialog appears and there he can select the image he wants. After he has made his decision I delete his current avatar and copy the new one in the same place with the same name. The avatar image is a rectangle with an imagebrush fill. The problem is that the image does not update until I restart the application. Here is the piece of code used to load the new image.

if (x.ShowDialog() == true)
{
    ImageBrush img = new ImageBrush();
    BitmapImage bit = new BitmapImage();
    Bitmap bmp = new Bitmap(x.FileName);
    System.IO.File.Delete(System.IO.Directory.GetCurrentDirectory() + "/data/images/avatar/x.png");
    bmp.Save(System.IO.Directory.GetCurrentDirectory() + "/data/images/avatar/x.png", System.Drawing.Imaging.ImageFormat.Png);

    bit.BeginInit();
    bit.CacheOption = BitmapCacheOption.OnLoad;
    bit.UriSource = new Uri(@"pack://siteoforigin:,,,/data/images/avatar/x.png");
    bit.EndInit();
    img.ImageSource = bit;
    ProfileImage.Fill = img;
}

I hope you can help me solve this issue or offer me some alternatives. Thank you all!

In order to make BitmapImage reload the image file (with identical file path), you could set the BitmapCreateOptions.IgnoreImageCache option:

bit.BeginInit();
bit.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bit.CacheOption = BitmapCacheOption.OnLoad;
bit.UriSource = new Uri(@"pack://siteoforigin:,,,/data/images/avatar/x.png");
bit.EndInit();
img.ImageSource = bit;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM