Home > OS >  How to add Stand-alone resource dictionaries in MAUI?
How to add Stand-alone resource dictionaries in MAUI?

Time:07-22

I'm reading the following tutorial to create a stand-alone resource dictionary :

I created a file in the folder Resources/Styles called "MyStyle.xaml" as :

<?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">
    <DataTemplate x:Key="PersonDataTemplate">
        <ViewCell>
            <Grid RowSpacing="6"
                  ColumnSpacing="6">
                ...
            </Grid>
        </ViewCell>
    </DataTemplate>
</ResourceDictionary>

I edited the file App.xaml as follows :

<?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:local="clr-namespace:MyApp"
             x:Class="MyApp.App">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
                <ResourceDictionary Source="Resources/Styles/MyStyle.xaml" /> <!-- Here -->
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

And in a page I added the dictionary :

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="PageName"
             Title="PageName">

    <ContentPage.Resources>
        <ResourceDictionary Source="MyStyle.xaml" /> <!-- Here -->
    </ContentPage.Resources>
    
    <VerticalStackLayout>
        <!-- something -->                      
    </VerticalStackLayout>
</ContentPage> 

I almost copy pasted the code in the official documentation page. But when compiling I'm getting the error :

XFC0124 Resource "MyStyle.xaml" not found.

Does anyone know what am I doing wrong please ?

Thanks.

CodePudding user response:

Just as Andrew said,you can try to add the following code in your page :

<ContentPage.Resources>
    <ResourceDictionary >

        <ResourceDictionary Source="Resources/Styles/MyStyle.xaml" />

    </ResourceDictionary>
</ContentPage.Resources>

CodePudding user response:

As Andrew said in comments you need MergedDictionaries

  <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/MyStyle.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
  • Related