【问题标题】:How to force Image control to close the file that it opens in wpf如何强制图像控件关闭它在 wpf 中打开的文件
【发布时间】:2023-03-21 10:58:01
【问题描述】:

我的 wpf 页面上有一个图像,它从硬盘打开一个图像文件。用于定义图像的 XAML 是:

  <Image  Canvas.Left="65" Canvas.Top="5" Width="510" Height="255" Source="{Binding Path=ImageFileName}"  />

我正在使用 Caliburn Micro,并且 ImageFileName 已更新为图像控件应显示的文件名。

当图像被图像控件打开时,我需要更改文件。但是该文件被图像控制锁定,我无法删除或复制任何法师。如何强制 Image 在打开文件后关闭文件,或者当我需要在其上复制另一个文件时?

我查了一下,没有用于图像的 CashOptio,所以我不能使用它。

【问题讨论】:

  • 发布您获取的 ImageFileName。你要在那里关闭文件吗?
  • @Blam:ImageFileName 是这样的:c:\tmp\testimage.jpg 我不会自己打开或关闭它。是 Image 控件打开它而不是关闭它。
  • this question and answer。在您的情况下,编写一个将文件名转换为 ImageSource 的绑定转换器可能是有意义的。
  • 没错。需要不同的模式,以便控件不访问文件。在转换器或 get 中执行此操作。

标签: c# wpf caliburn.micro


【解决方案1】:

您可以使用如下所示的binding converter,通过设置BitmapCacheOption.OnLoad 将图像直接加载到内存缓存中。文件会立即加载,之后不会锁定。

<Image Source="{Binding ...,
                Converter={StaticResource local:StringToImageConverter}}"/>

转换器:

public class StringToImageConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        object result = null;
        var path = value as string;

        if (!string.IsNullOrEmpty(path))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.UriSource = new Uri(path);
            image.EndInit();
            result = image;
        }

        return result;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

更好的是,直接从 FileStream 加载 BitmapImage:

public object Convert(
    object value, Type targetType, object parameter, CultureInfo culture)
{
    object result = null;
    var path = value as string;

    if (!string.IsNullOrEmpty(path) && File.Exists(path))
    {
        using (var stream = File.OpenRead(path))
        {
            var image = new BitmapImage();
            image.BeginInit();
            image.CacheOption = BitmapCacheOption.OnLoad;
            image.StreamSource = stream;
            image.EndInit();
            result = image;
        }
    }

    return result;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多