I have some code like this
_images = new ResourceDictionary
{
Source = new Uri(@"pack://application:,,,/Trilogy.T1TY2012.Transmission;component/Resources/Images.xaml")
};
which appears several times in my application (sometimes as C# and sometimes as the equivalent XAML). Does each instance contain separate instances of each of its resources, or is there a behind the scenes caching mechanism that shares those resources across all the resource dictionaries?
I am trying to decide if I need to make efficient use of the resource dictionaries (ie: share specific instances), or whether this optimization is already handled by WPF.
If I'm understanding your question, then the answer is, they are not "cached" *between different ResourceDictionary
instances: an instance of ResourceDictionary will not use any resource of the same type/key that may have been instantiated already in another ResourceDictionary. That is to be contrasted, of course, to keys within a single ResourceDictionary; each of those entries are indeed "cached", in the sense that they are created once and shared (with an exception for value-typed resources, which are copied on each use).
So, you do have to manage the scope of your resources if they are memory intensive. You can always put each resource into your main App.xaml
dictionary, which ensures each entry will be instantiated once, and shared for all its consumers. Note that the resources are lazy-loaded:
The items in a ResourceDictionary are not immediately processed when application code is loaded by a XAML loader. Instead, the ResourceDictionary persists as an object, and the individual values are processed only when they are specifically requested.
So you do not have to be concerned about your application loading all the resources in App.xaml on startup; it loads them only as needed.