Search code examples
wpfstartup

App OnStartup never gets called


Very simple problem but I'm making no progress so I thought I should ask...

I'm writing a small WPF prototype where I placed the boot up logics where I believe it belongs: In (the overridden) App.OnStartup method.

The problem is the method never gets called and I have no idea why!

I browsed around some and found someone saying the <Application> tag in App.xaml must specify the implementing class (App) in the "x:Class" attribute. I changed it from x:Class="Application" to x:Class="App" but it made no difference.

What am I missing here?

EDIT: Here's the code...

XAML:

<Application
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    x:Class="App"
    ShutdownMode="OnMainWindowClose"
    StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Recources\Brushes\Brushes.xaml"/>
                <ResourceDictionary Source="Recources\Templates\Templates.xaml"/>
                <ResourceDictionary Source="Recources\Styles\GVSStyles.xaml"/>
                <ResourceDictionary Source="Recources\Styles\TimePicker.xaml"/>
                <ResourceDictionary Source="Recources\Icons\GVSIcons.xaml"/>
                <ResourceDictionary Source="Recources\Icons\BottleIcon.xaml"/>
                <ResourceDictionary Source="Recources\Styles\BusyAnimationStyle.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

Code behind...

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);

    // lower default framerate from 60 to 20 to save CPU ...
    Timeline.DesiredFrameRateProperty.OverrideMetadata(
        typeof(Timeline),
        new FrameworkPropertyMetadata { DefaultValue = 20 });

    hookUpViews();
    connectToServer();
}

Solution

  • Edit: Your XAML seems to not be associated with the code behind, the x:Class needs to include the namespace of your App class. e.g. MyWpfApplication.App.


    Unless you post some code you just get wild guessing, here's mine: You didn't properly override the method but hide it with a method of the same name and signature.

    This is what a working override should look like:

    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        MessageBox.Show("!");
    }
    

    As suggested you can use the Startup event instead, but you don't have to, further the StartupUri will be executed in addition to the code in the override.