P3PPP P3PPP - 1 month ago 53
C# Question

Xamarin.Forms: How can I load ResourceDictionary from another file?

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>

Answer

Merged Dictionaries aren't supported in Xamarin Forms XAML below 2.1.0

The only way you can do it, is to put it in another page and then load it up in code behind and reference it via DynamicResource instead of StaticResource.

I explain this more here: http://www.xamarinhelp.com/styling-uiux-day-11/

However as of 2.1.0-pre1 (released this week), you can now do templating, which is another way to do this. Jason Smith has blogged about it: http://xfcomplete.net/general/2016/01/20/control-templates/

As of 2.3.0 you can do a Merged Dictionary with an attribute called MergedWith.

Create a new XAML File

<?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="UIDemo.Style.NewStyle">
    <Style TargetType="Label">
        <Setter Property="TextColor" Value="Blue" />
    </Style>
</ResourceDictionary>

Now in your ContentPage use the MergedWith attribute on your ResourceDictionary.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:theme="clr-namespace:UIDemo.Style"
             x:Class="UIDemo.MainPage">
    <ContentPage.Resources>
        <ResourceDictionary MergedWith="theme:NewStyle" />
    </ContentPage.Resources>
    <Grid>
        <Label Text="Hello" />
    </Grid>
</ContentPage>