Search code examples
c#wpfxamlresourcedictionaryxamlreader

loading a ResourceDictionary from an XAML also loads files into memory


I have an XAML file that I load it as a ResourceDictionary using

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();
                }

inside that XAML, I have an ImageBrush. When I read the dictionary,MyApplication.vshost.exe is now using the image file that forms the ImageBrush. i.e. the file that in the Source property of the ImageBrush. I need to delete that file but it gives an error because the file is in use by another process. My question is how to do this properly so that the file is free to be deleted later.


Solution

  • You may set BitmapCacheOption.OnLoad on a BitmapImage in your ImageBrush resource by writing it like this:

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