我有一些这样的代码
_images = new ResourceDictionary
{
Source = new Uri(@"pack://application:,,,/Trilogy.T1TY2012.Transmission;component/Resources/Images.xaml")
};它在我的应用程序中出现了几次(有时作为C#,有时作为等效的XAML)。每个实例是否包含其每个资源的单独实例,或者是否存在在所有资源字典之间共享这些资源的幕后缓存机制?
我正在尝试决定是否需要有效地使用资源字典(例如:共享特定的实例),或者这种优化是否已经由WPF处理。
发布于 2012-12-20 13:40:22
如果我理解你的问题,那么答案是,它们不会在不同的ResourceDictionary实例之间“缓存”*:ResourceDictionary的实例不会使用任何已经在另一个ResourceDictionary中实例化的相同类型/键的资源。当然,这将与单个ResourceDictionary中的键形成对比;这些条目中的每一个确实都是“缓存”的,因为它们只创建一次并共享(值类型的资源除外,它们在每次使用时都会被复制)。
因此,如果资源是内存密集型的,那么您必须管理资源的范围。您始终可以将每个资源放入您的主App.xaml字典中,这确保每个条目将被实例化一次,并为其所有使用者共享。请注意,the resources are lazy-loaded
XAML加载器加载应用程序代码时,不会立即处理ResourceDictionary中的项。相反,ResourceDictionary将作为对象持久存在,并且仅在明确请求单个值时才对其进行处理。
因此,您不必担心应用程序在启动时加载App.xaml中的所有资源;它只在需要时加载它们。
发布于 2016-04-19 20:21:54
拥有一个不会为每次用法实例化的字典
/// <summary>
/// The shared resource dictionary is a specialized resource dictionary
/// that loads it content only once. If a second instance with the same source
/// is created, it only merges the resources from the cache.
/// </summary>
public class SharedResourceDictionary : ResourceDictionary
{
/// <summary>
/// Internal cache of loaded dictionaries
/// </summary>
public static Dictionary<Uri, ResourceDictionary> _sharedDictionaries =
new Dictionary<Uri, ResourceDictionary>();
/// <summary>
/// Local member of the source uri
/// </summary>
private Uri _sourceUri;
/// <summary>
/// Gets or sets the uniform resource identifier (URI) to load resources from.
/// </summary>
public new Uri Source
{
get { return _sourceUri; }
set
{
_sourceUri = value;
if (!_sharedDictionaries.ContainsKey(value))
{
// If the dictionary is not yet loaded, load it by setting
// the source of the base class
base.Source = value;
// add it to the cache
_sharedDictionaries.Add(value, this);
}
else
{
// If the dictionary is already loaded, get it from the cache
MergedDictionaries.Add(_sharedDictionaries[value]);
}
}
}
}对于资源本身,您可以使用x:shared属性
https://stackoverflow.com/questions/13965694
复制相似问题