首页 文章

WPF更改图像路径并在运行系统中显示新图像

提问于
浏览
0

我有WPF图像,它的来源是我的硬盘上的本 Map 像URI,我正在使用转换器来加载它 .

我想改变硬盘上的图像(用另一个替换它),然后在 runtime 中显示新图像

这里是图像的XAML

<Image  Stretch="Fill">
                                            <Image.Style>
                                                <Style TargetType="Image">
                                                    <Setter Property="Source" Value="{Binding ImagePath,Converter={StaticResource ImageFileLoader},UpdateSourceTrigger=PropertyChanged}"/>
                                                </Style>
                                            </Image.Style>
                                        </Image>

这是转换器

class ImageFileLoader : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value != null)
        {
            string filePath = value.ToString();
            if (File.Exists(filePath))
            {
                BitmapImage result = new BitmapImage();
                result.BeginInit();
                result.UriSource = new Uri(filePath);
                result.CacheOption = BitmapCacheOption.OnLoad;
                result.EndInit();
                return result;
            }

        }

        return null;
    }

}

注意:我试图将转换器中的 CacheOption 更改为 BitmapCacheOption.None 或任何其他选项......它不起作用,因为在这种情况下我无法改变硬盘上的图像

1 回答

  • 2

    当框架加载 Image 时,它会对其产生令人讨厌的影响,因此,如果您尝试删除或移动实际的图像文件,您将会收到类似无法访问该文件的内容,因为它正在被使用 . 为了解决这个问题,我创建了一个类似于你的 IValueConverter ,以便将 Image.CacheOption 设置为 BitmapCacheOption.OnLoad ,在加载时将整个图像缓存到内存中,从而删除保留 .

    但是,我的Converter中的代码看起来与你的相似,所以我_533405为你工作 . 这是我的 IValueConverter 代码:

    using (FileStream stream = File.OpenRead(filePath))
    {
        image.BeginInit();
        image.StreamSource = stream;
        image.CacheOption = BitmapCacheOption.OnLoad;
        image.EndInit();
    }
    

相关问题