自定义图片框中的图像无法刷新更新

4

我的自定义图片框包含一个滚动视图和一张图片。 使用类型为字符串的依赖属性Image来设置图片。

public static DependencyProperty ImageProperty = DependencyProperty.Register(
"Image", typeof(string), typeof(CustomPictureBox), new FrameworkPropertyMetadata("", new  PropertyChangedCallback(OnImageChanged)));


private static void OnImageChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
  CustomPictureBox cpb = (CustomPictureBox)d;
  if (e.Property == ImageProperty)
  {
    string newvalue = e.NewValue as string;
    if (!(string.IsNullOrEmpty(newvalue)))
    {
      var bmp = new BitmapImage();
      bmp.BeginInit();
      bmp.UriSource = new Uri(newvalue);
      bmp.CacheOption = BitmapCacheOption.OnLoad;
      bmp.EndInit();

      cpb.imgPicture.Source = bmp;
    }
    else
      cpb.imgPicture.Source = null;
  }
}

通过帧抓取器获取图像并将其存储到给定位置,文件名为“camera_image.tif”。设置Image属性为该文件名。当开始新的图像采集时,通过绑定将Image属性设置为空,并更新图像框以显示无图像。当图像采集完成时,再次将其设置为“camera_image.tif”。问题是新图像从未显示过,而是始终显示第一个采集到的图像。当检查图像文件时,它包含了新内容。如何刷新图像框以显示新图像?

你已经移除了CacheOption吗?把整行代码删掉:bmp.CacheOption = BitmapCacheOption.OnLoad; - Aaron McIver
如果我这样做,第二次图像采集将失败,因为它无法将结果写入文件“camera_image.tif”。 - tabina
我希望用户能够进行以下操作:1)获取图像,2)通过显示图像给用户确认是否正确,3)如果正确:将其保存到不同的文件位置,4)如果不正确:重新尝试并获取另一张图像... - tabina
OnLoad 会关闭流,而 OnDemand 则不会,这是默认行为。 - Aaron McIver
显然,我需要关闭流才能从其他地方访问文件。有没有办法告诉<Image>释放其缓存?或者需要执行哪些其他操作才能正确显示位图? - tabina
1个回答

10

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接