Thanks @mm8 for posting your answer. It's 100% correct, I just want to post my own answer, because I found out something interesting, that can be useful for someone else.
The answer is: ResourceDictionary instance will be created just once if referenced in the application (no matter many controls uses its styles), BUT it will be instantiated again for every time it is referenced in another ResourceDictionary that is also used in the application.
So to give you example of this case let's say we have the following structure:
- StylesAssembly.dll
- ButtonResourceDictionary.xaml
- CustomButtonResourceDictionary.xaml
- Application.exe
- App.xaml
- MainWindow.xaml
ButtonResourceDictionary.xaml has the following code:
<Style x:Key="DefaultButtonStyle" TargetType="{x:Type Button}">
<!-- Some setters -->
</Style>
CustomButtonResourceDictionary.xaml has the following code, which uses ButtonResourceDictionary.xaml
:
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="ButtonResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
<Style x:Key="CustomButtonStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource DefaultButtonStyle}">
<!-- Some setters -->
</Style>
Application.exe
has a reference to StylesAssembly.dll
and there is a following code in the App.xaml:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/StylesAssembly;component/ButtonResourceDictionary.xaml" />
<ResourceDictionary Source="pack://application:,,,/StylesAssembly;component/CustomButtonResourceDictionary.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
Now if our MainWindow.xaml has something like this in it, the ButtonResourceDictionary.xaml
will have only one instance:
<StackPanel>
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
</StackPanel>
but if our MainWindow.xaml has something like this in it, the CustomButtonResourceDictionary.xaml
will have one instance, but the ButtonResourceDictionary.xaml
will have two instances:
<StackPanel>
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource DefaultButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
<Button Style="{StaticResource CustomButtonStyle}" />
</StackPanel>
It happens because first two Buttons
use style DefaultButtonStyle
from ButtonResourceDictionary.xaml
, but another three Buttons
use style CustomButtonStyle
which comes from CustomButtonResourceDictionary.xaml
, which merges ButtonResourceDictionary.xaml
in its code.