【问题标题】:Image Control in Wpf showing previous image which was deletedWpf 中的图像控件显示已删除的上一个图像
【发布时间】:2015-02-25 11:49:40
【问题描述】:

我有一个显示预览图像的图像控件。如果用户删除图像(位于文件夹中),它应该显示新拍摄的图像。 但是图像控件显示的是删除的图像,而不是显示新的图像。

// clear the image source before deleting the image.

// save image in the directory
public string globalFilePath;

int imageCount = Directory.GetFiles(imgDir, "*", SearchOption.TopDirectoryOnly).Length;

string filePath = Path.Combine(imgDir, "IMAGE_" + ++imageCount + ".jpeg");
globalFilePath = filePath;

// setting image control source

var strUri = new Uri(WebCamControl.globalFilePath, UriKind.Relative);
previewImage.Source = BitmapFromUri(strUri);

//Method
public static ImageSource BitmapFromUri(Uri source)
    {
        var bitmap = new BitmapImage();
        bitmap.BeginInit();
        bitmap.UriSource = source;
        bitmap.CacheOption = BitmapCacheOption.OnLoad;
        bitmap.EndInit();
        return bitmap;
    }

// delete image

previewImage.Source =  null; 

if (System.IO.File.Exists(WebCamControl.globalFilePath))
{
    System.IO.File.Delete(WebCamControl.globalFilePath);
}
else
{
    MessageBox.Show("File Not Exists");
}

删除目录文件中的图像后,图像图像控件应显示新图像,但我的图像控件显示已删除的图像。请给我解决方案。

【问题讨论】:

  • 成功加载后会显示新的图片。此代码未显示如何/何时加载 next 图像。
  • 删除文件系统中的图片后,会重新拍摄新的图片并默认保存。我得到该路径并将其分配给图像控制源。 @Henk
  • 我发现我保存新图像的名称与已删除图像的名称相同的问题,我改变了为新图像创建名称的方式。感谢您的帮助:)

标签: c# wpf


【解决方案1】:

在 WPF 中,我们一般不需要使用实际的BitMapImage 对象来显示Image。让 .NET Framework 将我们的 string 文件路径转换为图像到实际的 Image 元素要容易得多。

此外,将Image.Source 数据绑定到实现INotifyPropertyChanged interface(或DepenedencyProperty)的属性更好:

<Image Source="{Binding YourImageFilePath}" ... />

然后,只要将新图像的文件路径设置为YourImageFilePath 属性,您显示的图像就会立即更新。

YourImageFilePath = filePath;

【讨论】:

  • 实际上我不知道 INotifyPropertyChanged 接口或 DepenedencyProperty 。你能告诉我怎么做吗?
  • 我为INotifyPropertyChanged添加了一个指向MSDN的链接。
  • 我正在我的类本身中实现 ​​INotifyPropertyChanged,例如 (public partial class MainWindow : INotifyPropertyChanged) 是不是很正式?
  • 您需要在声明您的属性的任何类中实现它,以便您可以在它们的值更改时通知。
  • 我已经实现了 Inotifypropertychanged 接口,但是 Image 控件什么也没显示。我已经创建了 Image conerter 来转换图像,但甚至没有用。 @谢里丹
【解决方案2】:

试试这个:

    string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.SetValue(System.Windows.Controls.Image.SourceProperty, null);
File.Delete(path);

string path = ((BitmapImage)img.Source).UriSource.LocalPath;
img.Source = null;
File.Delete(path)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-17
    • 2011-02-23
    • 2011-05-18
    相关资源
    最近更新 更多