How to effectively use the resource dictionary in all parts of the project

I use the resource dictionary (the same dictionary) in many converters as a local variable.

var DeignerDictionary = new ResourceDictionary { Source = new Uri(path) }; 

Every time I create a new instance, and the memory takes up a lot of space in the application.

Then I moved the resource dictionary to a static field and I reused the dictionary, but the styles do not display correctly.

 public class resourceDictionaryProvider{ public readonly ResourceDictionary StaticDictionary = new ResourceDictionar {Source = new Uri(path)}; } 

Can anyone suggest what I am doing wrong, please submit your suggestions.

The problem occurs after changing the ResourceDictionary as static only. But the following code is working fine.

 public class resourceDictionaryProvider{ public static readonly ResourceDictionary StaticDictionary = new ResourceDictionar {Source = new Uri(path)}; } 

Now I am creating an instance of the resourceDictionaryProvider class and it works fine, but I do not want to instantiate. So only I changed it to static.

What is the problem with the static keyword?

+5
source share
2 answers

This is a well known issue with WPF ResourceDictionaries. The solution would be to implement our own SharedResourceDictionary, which prevents the re-creation of resources with every use. Take a look at this link: WPF SharedResourceDictionary for a terrific implementation of the SharedResourceDictionary construct. (All credits to the author)

+3
source

You must solve two problems:

  • Resource dictionaries can be shared between the modules of your project or solution;
  • It would be convenient to have a development-time resource dictionary to help with style settings.

To solve problem # 1, it's easy to add your resource dictionaries to the App.xaml file, and then they will be created once and will be available for the entire project, for example:

 <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="pack://application:,,,/Themes;component/Generic.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> 

To solve problem # 2, you will need a workaround that a resource dictionary will be created only during development. Check out the development time resource dictionary

and then you can use DesignTimeResourceDictionary for your user interfaces, for example:

 <Window.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <designer:DesignTimeResourceDictionary Source="pack://application:,,,/Themes;component/Generic.xaml" /> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Window.Resources> 
+1
source

Source: https://habr.com/ru/post/1259721/


All Articles