Cannot access resource defined in app.xaml
If you've set the Startup Object to a custom class you need to create the custom Application class and also call its InitializeComponent method, like this:
App app = new App();
app.InitializeComponent();
Update: As @qqww2 suggested the InitializeComponent
call can be moved inside the App
class constructor.
I start my application not with a StartupUri
in App.xaml
, but with a event handler in App.xaml.cs
.
When using override Startup()
resources from App.xaml are not loaded:
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
...
}
}
But when using event Startup
the resources are loaded just fine:
<Application x:Class="OxyplotTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="OnStartup">
And code behind:
public partial class App
{
private void OnStartup(object sender, StartupEventArgs e)
{
...
}
}
Nothing you have done is incorrect. You either have 1) screwed up the project build somehow while randomly doing things to try to get it to work or 2) something else is going on here and we'll never know without the exception details.
I would highly suggest you try to repro this in a fresh brand new WPF project. Do the following steps (and ONLY the following steps):
Create a new WPF project, add the exact same brush to app.xaml, then open Window1 and bind the window's background to the resource. Run the app.
It should work as expected. If not, come back with the exception details. If it does, compare this new project with your current one to see what you are doing differently.
I know there is an already accepted answer, but I thought I would add my solution as well. I had code that was working, but some configuration change broke the resource references in the designer. In executing code, it worked fine.
After some initial research, I determined that the BuildAction property for App.xaml should be set to ApplicationDefinition. My was set to Page. However, that causes some issues with multiple entry points. Main() was already defined in App.xaml.cs. The compile error was indicating another entry point in App.g.cs (which is an autogenerated file).
I ended up using the approach #3 described at http://www.infosysblogs.com/microsoft/2008/09/how_to_write_custom_main_metho.html. The basic idea is that you create a new class that is only responsible for startup. In my case, I named it Startup.cs. It should have code that is similar to this:
using System.Threading;
namespace MyNamespace
{
public class Startup
{
[System.STAThreadAttribute()]
private static void Main()
{
var app = new App();
app.InitializeComponent();
app.Run();
}
}
}
Then in the project settings, change the Application -> Startup object so that your new class is selected.