1

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.

Adam Diament
  • 4,290
  • 3
  • 34
  • 55
  • If you move the style from styles.xaml to app.xaml, does DynamicResource work? If so, then either do that, or in app.xaml.cs, after InitializeComponent, copy the keyvalue pairs from style.xaml directly into app resources (doing so should be equivalent to defining it in app.xaml). – ToolmakerSteve Jul 02 '23 at 21:24

1 Answers1

0

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.

Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14