Use keys from one dotnet Maui resource dictionary file in another resource dictionary file

523 Views Asked by At

I have two resource dictionary files, Colors.xaml and Styles.xaml

I consume them from App.xaml like this

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

I want nodes in Styles.xaml to be able to use keys from Colors.xaml

Such as this in Colors.xaml

  <Color x:Key="MySpecialColor">#0000FF</Color>
 <Setter Property="TextColor" Value="{StaticResource MySpecialColor}" />

The app compiles and I can even control+click in VS2022 from the usage of MySpecialColor in Styles.xaml and it goes to the correct place in Colors.xaml, but at runtime I get this error

[mono-rt]  ---> Microsoft.Maui.Controls.Xaml.XamlParseException: Position 25:58. StaticResource not found for key MySpecialColor

This answer from a relatively similar question about WPF not Maui, suggests using a DynamicResource instead of a static resource. This doesn't work for Maui, I get the same error. Plus even if it did, I would like to statically type it if I can.

1

There are 1 best solutions below

4
Liyun Zhang - MSFT On

First of all, did you check the default maui project template? There are two resource dictionaries in the /Resources/Styles folder : Colors.xaml and Styles.xaml.

    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources/Styles/Colors.xaml" />
                <ResourceDictionary Source="Resources/Styles/Styles.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>

And the key in the Colors.xaml is used in the Styles.xaml. And I also tried to add a custom color in Colors.xaml:

  <Color x:Key="MyColor">#0000FF</Color>

And use it for the Button's style:

<Style TargetType="Button">
        <Setter Property="TextColor" Value="{StaticResource MyColor}" />

And the button's text color will be changed.