从XAML加载ResourceDictionary还会将文件加载到内存中

时间:2014-07-17 10:34:12

标签: c# wpf xaml resourcedictionary xamlreader

我有一个XAML文件,我使用

将其作为ResourceDictionary加载
using (FileStream fs = new FileStream(path, FileMode.Open))
                {
                    // Read in ResourceDictionary File
                    ResourceDictionary dic =
                       (ResourceDictionary)XamlReader.Load(fs);

                    // Clear any previous dictionaries loaded
                    Application.Current.Resources.MergedDictionaries.Clear();
                    // Add in newly loaded Resource Dictionary
                    Application.Current.Resources.MergedDictionaries.Add(dic);
                    fs.Close();
                }
在XAML里面,我有一个ImageBrush。当我阅读字典时,MyApplication.vshost.exe现在正在使用构成ImageBrush的图像文件。即ImageBrush的Source属性中的文件。我需要删除该文件,但它会出错,因为该文件正由另一个进程使用。我的问题是如何正确地执行此操作,以便以后可以自由删除该文件。

1 个答案:

答案 0 :(得分:1)

您可以在BitmapImage资源的ImageBrush上设置BitmapCacheOption.OnLoad,方法如下:

<ImageBrush x:Key="myImageBrush">
    <ImageBrush.ImageSource>
        <BitmapImage UriSource="..." CacheOption="OnLoad"/>
    </ImageBrush.ImageSource>
</ImageBrush>