I wrote following code, but XamlParseException has bean thrown. ("StaticResource not found for key CustomColor")
MyPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="XFApp11.MyPage">
<ContentPage.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="CustomResource.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</ContentPage.Resources>
<ContentPage.Content>
<BoxView Color="{StaticResource CustomColor}" />
</ContentPage.Content>
</ContentPage>
CustomResource.xaml (build action = EmbeddedResource)
<?xml version="1.0" encoding="UTF-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
<Color x:Key="CustomColor">#004B86</Color>
</ResourceDictionary>
To add more than one dictionary, just add a <ResourceDictionary Source="Dictionary2. xaml"/> entry after the first entry.
A resource dictionary is a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension s. You can also access resources with code, but that is less common.
A ResourceDictionary is a repository for resources that are used by a Xamarin. Forms application. Typical resources that are stored in a ResourceDictionary include styles, control templates, data templates, colors, and converters.
From Xamarin.Forms 3.0 MergedWith has been deprecated and should not be used.
Now you can use either Source or MergeDictionaries.
MyResource.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="UI.MyResource">
<Style TargetType="Label">
<Setter Property="TextColor" Value="Blue" />
</Style>
</ResourceDictionary>
So, if MyResource.xaml is in the same assembly you can use directly:
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="UI.AnotherResource"
Source="MyResource.xaml">
</ResourceDictionary>
Otherwise (MyResource.xaml is on another assembly):
<?xml version="1.0" encoding="utf-8" ?>
<ResourceDictionary xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:otherresources="clr-namespace:OtherAssembly.UI.Resources"
x:Class="UI.AnotherResource">
<ResourceDictionary.MergedDictionaries>
<otherresources:MyResource />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
Some things to take into consideration:
More info in Xamarin Forms Resource Dictionaries
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