C# 从XAML加载ResourceDictionary也会将文件加载到内存中
我有一个XAML文件,我使用它作为ResourceDictionary加载C# 从XAML加载ResourceDictionary也会将文件加载到内存中,c#,wpf,xaml,resourcedictionary,xamlreader,C#,Wpf,Xaml,Resourcedictionary,Xamlreader,我有一个XAML文件,我使用它作为ResourceDictionary加载 using (FileStream fs = new FileStream(path, FileMode.Open)) { // Read in ResourceDictionary File ResourceDictionary dic = (ResourceDi
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的图像文件。i、 e.ImageBrush的源属性中包含的文件。我需要删除该文件,但它给出了一个错误,因为该文件正由另一个进程使用。我的问题是如何正确地执行此操作,以便以后可以自由删除该文件 您可以在ImageBrush
资源中设置BitmapImage
,方法如下:
<ImageBrush x:Key="myImageBrush">
<ImageBrush.ImageSource>
<BitmapImage UriSource="..." CacheOption="OnLoad"/>
</ImageBrush.ImageSource>
</ImageBrush>
请注意:无需调用fs.Close()
,因为在退出using块时,流会自动处理。感谢您的回复,这似乎是问题的根源。当我手动编辑XAML以添加上面的CacheOption代码时,它没有问题。但是,手动编辑不是一个选项,自动编辑将要求我首先加载XAML,但是如果我首先加载它,这将产生完全相同的错误。我设法将其作为XDocument加载。我将其修改为如上所述,然后这次将其作为ResourceDictionary再次加载。效果很好