We start with one project WPF application and the resource dictionary included in main window dictionary.
1: <Window x:Class="WpfApplication.MainWindow"
7: <!--Some styles here-->
11: <!--some controls here-->
and we want to extract the styles from section Window.Resources, place them in separate dictionary file and in separate assembly. First we add a class library project to our solution and name it for example CustomStyles. Then we add an xml file to this library and name it for example Styles.xaml. Our solution now looks similar to this
Then we copy whole styles from MainWindow.xaml to the Styles.xaml and place it in ResourceDictionary element
1: <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3: <!--All styles here-->
Then in MainWindow.xaml we reference the styles
4: <ResourceDictionary Source="pack://application:,,,/CustomStyles;component/Styles.xaml" />
The syntax of the source value is determined by The Pack URI Theme. The only thing to do is now to add to the main application the reference of CustomStyles assembly.
Problems you might encounter:
- There is an error in CustomAssembly build which says “Library project file cannot specify ApplicationDefinition element.”
Solution: Check the BuildAction of the Styles.xaml file. It should be set to Page. Sometimes, when you copy files between projects Visual Studio automatically changes its build action. You can change the build action of the file by clicking the right button on it and choosing Properties.
- During execution of the wpf application following error occurs: “Cannot locate resource …”
Solution: Check the resource assembly is properly referenced in the application project. Check the pack uri for the misspelling. It should be in format pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml where pack://application:,,,/ and component are constant part. If you place you xaml file in a subfolder then you must include it in the uri as shown above.