I am using resource dictionary(same dictionary) in many converters as a local variable.
var DeignerDictionary = new ResourceDictionary
{
Source = new Uri(path)
};
Each time I am creates a new instance and the memory goes very high in the application.
Then I have moved the resource dictionary into a static field and I am reusing the dictionary , but the styles are not rendered properly.
public class resourceDictionaryProvider{
public readonly ResourceDictionary StaticDictionary =
new ResourceDictionar {Source = new Uri(path)};
}
Can anyone suggest what I am doing wrong,Please provide your suggestions.
The issue occurs after changed the ResourceDictionary as static only.But the following code works fine.
public class resourceDictionaryProvider{
public static readonly ResourceDictionary StaticDictionary =
new ResourceDictionar {Source = new Uri(path)};
}
Now I am creating an instance for resourceDictionaryProvider class and it works fine,But I don't want to create instances So only I have changed it to static.
What is the problem with the static keyword here?
This is a well known problem with WPF ResourceDictionaries. The solution would be to implement a SharedResourceDictionary construct on your own which prevents re-instantiation of the resources on each use. Take a look at this link : WPF SharedResourceDictionary for an awesome implementation of the SharedResourceDictionary construct.( All credits to the author )
There are two issues you need to address:
To solve the issue #1, it's easy to add your resource dictionaries to the App.xaml file, and then they will be instantiated once, and will be available to the entire project, like this:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary
Source="pack://application:,,,/Themes;component/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
To solve the issue #2, you need a workaround solution that the resource dictionary is instantiated at the design time only. Check out Design time resource dictionary
and then, you can use the DesignTimeResourceDictionary on your UIs, like this:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<designer:DesignTimeResourceDictionary
Source="pack://application:,,,/Themes;component/Generic.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With