Search code examples
c#wpfxamlcode-behindapp.xaml

app.xaml resources won't work. dot.net core stuff?


I had the following resources defined in the app.xaml file, that worked perfectly:

<Application.Resources>
    <Style TargetType="Button" x:Key="homeButtom">
        <Setter Property="Margin" Value="5" />
        <Setter Property="Padding" Value="4" />
        <Setter Property="Width" Value="110" />
        <Setter Property="Background" Value="CadetBlue" />
        <Setter Property="Foreground" Value="White" />
        <Setter Property="FontSize" Value="14" />
    </Style>
</Application.Resources>

Then, I added entity framework to the solution and, as recommended, O removed the "StartupUri="MainWindow.xaml" from the header and inserted the call in the code behind:

protected override async void OnStartup(StartupEventArgs e)
    {
        await host.StartAsync();

        var mainWindow = host.Services.GetRequiredService<MainWindow>();
        mainWindow.Show();

        base.OnStartup(e);
    }

And the resources won't work unless it's set on the pages it's needed.

Just adding, that I guess that's the reason. The fact is that my resources just work from app.xaml...


Solution

  • I can confirm that the way you have presented the resource, it doesn't work in dot net core. However, I found that if you place your resource inside of a ResourceDictionary, it will work.

    App.xaml.cs:

            <ResourceDictionary>
                <ResourceDictionary.MergedDictionaries>
                    <ResourceDictionary Source="pack://application:,,,/MyResourceDictionary.xaml"/>
                </ResourceDictionary.MergedDictionaries>
            </ResourceDictionary>
    

    MyResourceDictionary.xaml:

        <Style TargetType="Button" x:Key="homeButtom">
            <Setter Property="Margin" Value="5" />
            <Setter Property="Padding" Value="4" />
            <Setter Property="Width" Value="110" />
            <Setter Property="Background" Value="CadetBlue" />
            <Setter Property="Foreground" Value="White" />
            <Setter Property="FontSize" Value="14" />
        </Style>