WPF provides DynamicResources for this very reason. StaticResources - which are most reminiscent of the "traditional" links in programming - there is only the problem you are facing; they must be defined and loaded before the style is analyzed. On the other hand, DynamicResources need not be defined until they are used - indeed, you can even create them on the fly. WPF makes sure that DynamicResources is automatically loaded with all styles that reference them after they are actually loaded.
Using DynamicResources is simple. When you create a MonkeyText style, create it as usual:
<Style TargetType="TextBlock" x:Key="MonkeyText"> <Setter Property="TextAlignment" Value="Center"/> </Style>
And then access it from another source using DynamicResource:
<TextBlock Text="Hello, World!" Style="{DynamicResource MonkeyText}"/>
If for some reason WPF cannot resolve your DynamicResource, it will fail without any exceptions (StaticResources really throw exceptions if they cannot be resolved). However, it will print a debugging message when this happens - keep an eye on the output window in Visual Studio.
Since DynamicResources work with resources that are loaded at any time in any order, you can structure your resource dictionaries in any way you like - thus, inserting them into your other view styles and combining them through a single App.Resources ResourceDictionary file in app.xaml will work fine.
More about DynamicResources can be found in the MSDN docs for WPF.
Nicholas armstrong
source share