简体   繁体   中英

Styles in MergedDictionaries not found

I keep getting a runtime error StaticResource not found for key when using a Style in a ResourceDictionary that's merged by means of MergedDictionaries .

App.xaml

   <Application x:Class="MyApp.App"
             xmlns:local="MyApp"
             xmlns:assets="clr-namespace:MyApp.Assets">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <assets:Styles />
            </ResourceDictionary.MergedDictionaries>
                 <Style ...>
                    <!-- other styles... -->

Styles.xaml

<ResourceDictionary x:Class="MyApp.Assets.Styles">
    <Style x:Key="Subheading" TargetType="Frame">
        <Setter Property="BackgroundColor" Value="DarkSlateGray"></Setter>
        <Setter Property="HasShadow" Value="True"></Setter>
    </Style>
</ResourceDictionary>

Styles.xaml.cs

namespace MyApp.Assets
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Styles : ResourceDictionary
    {
        public Styles () { }
    }
}

Page.xaml

        <Frame Style="{StaticResource Subheading}">

The app compiles correctly -- it just can't find Subheading at runtime. If I copy the <Style> node directly into App.xaml, it works fine. Can anyone find my incorrect syntax? Or, is there a way, at runtime, to look at Application.Resources so I can figure out where it is?

You're missing an InitializeComponent() method call inside of your Styles constructor. Do it like this:

namespace MyApp.Assets
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Styles : ResourceDictionary
    {
        public Styles()
        {
            InitializeComponent();
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM