RelativeLayouter
RelativeLayouter

Reputation: 393

MAUI: Unable to share ResourceDictionaries between two SDK-style projects

I have two SDK-style MAUI projects, let's say Project1 and Project2. Project2 has following structure:

Project2.sln
    |
    - Resources
        |
        - Colors.xaml

Colors.xaml has the following code:

<?xml version="1.0" encoding="UTF-8" ?>
<?xaml-comp compile="true" ?>
<ResourceDictionary xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
                    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                    x:Class="Project2.Resources.Colors">

    <Color x:Key="TestColor">#512BD4</Color>

</ResourceDictionary>

The goal is to use TestColor in Project1, maybe later in Project3, Project4, and so on. As long as standard WPF-like XAML notation does not work in MAUI, we have to include this file as following:

Project1/App.xaml:

<?xml version="1.0" encoding="utf-8" ?>
<Application xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:resources="clr-namespace:Project2.Resources;assembly=Project2"
             x:Class="Project1.App">

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <resources:Colors />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

</Application>

This one at least can compile without errors, but that does not work. When i am trying to use new static resource in some king of view, like this:

Project1/MainWindow.xaml:

<Grid BackgroundColor="{StaticResource TestColor}" />

It throws a runtime error Microsoft.Maui.Controls.Xaml.XamlParseException: 'Position XX:XX. StaticResource not found for key TestColor' and IntelliSense having no clue about TestColor so. The question is: how do i need to properly link my external ResourceDictionary in other projects using MAUI?

Upvotes: 2

Views: 846

Answers (1)

ToolmakerSteve
ToolmakerSteve

Reputation: 21321

Workaround: During app startup, manually copy all the entries in the dll's resourcedictionary into Application.Current.Resources.
In shared App.xaml.cs:

public App()
{
    InitializeComponent();

    // TODO: Code to get dll's resourcedictionary.
    ResourceDictionary rd1 = ...;   // Project2.Resources?

    // Copy all entries into app's Resources.
    foreach (KeyValuePair<string, object> entry in rd1)
    {
        Application.Current.Resources[entry.Key] = entry.Value;
    }

    MainPage = new AppShell();  // Or whatever you have here.
}

TODO: Code to get dll's resourcedictionary.

I haven't worked with dll's in Maui, so not certain the code you need for this step.

Upvotes: 0

Related Questions