<Page x:Class="MyNewApp.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:MyNewApp" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d"> <Page.Resources> <!-- Creates a resource dictionary in the page context --> <ResourceDictionary> <!-- This is a solid color brush resource NOTE: Each resource inside a resource dictionary must have a key --> <SolidColorBrush x:Key="ColorRed">Red</SolidColorBrush> </ResourceDictionary> </Page.Resources> <!-- Using ThemeResource in here to access a resource already defined --> <Grid Background="{ThemeResource ColorRed}"> </Grid> </Page>
Resource dictionaries are accessible only inside the context they were declared, so if we intended to reference resources that are declared in one page context from another page they will not be found. So if we need global resources to be defined like the ones that comes with the framework we do it in App.xaml
<Application x:Class="MyNewApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" RequestedTheme="Dark"> <Application.Resources> <ResourceDictionary> <SolidColorBrush x:Key="ColorRed">Red</SolidColorBrush> </ResourceDictionary> </Application.Resources> </Application>
This way we can access ColorRed
color resource from anywere in our app. But wait, we don't want to infest that little file with all our app's resources! So we do MergedDictionaries
Almost usually things are a little bit more complex and to support scalability we should split things apart. So we can define various files containing different resources dictionaries, i.e. resources for UI controls' themes, resources for texts and so on, then we merge them all together in App.xaml file.
<Application x:Class="MyNewApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" RequestedTheme="Dark"> <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <ResourceDictionary Source="/Assets/Themes/GeneralStyles.xaml"/> <ResourceDictionary Source="/Assets/Themes/TemplatedControls.xaml"/> <ResourceDictionary Source="/Assets/Strings/Texts.xaml"/> <ResourceDictionary Source="/Assets/Strings/ErrorTexts.xaml"/> </ResourceDictionary.MergedDictionaries> </ResourceDictionary> </Application.Resources> </Application>
You can create a new dictionary file by right clicking on Asset folder [Add -> New Item]
We now need to access to our declared resources, in order to do that from XAML code we use {ThemeResource ResourceKey}
or {StaticResource ResourceKey}
to be continued later.