Tomasz Grobelny
Tomasz Grobelny

Reputation: 2746

force instantiation of xaml resource

Let's consider a WPF application with the following XAML (App.xaml):

<Application
  x:Class="My.App"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:my="clr-namespace:My.Namespace;assembly=My.Assembly"
  ShutdownMode="OnExplicitShutdown"
  >
  <Application.Resources>
    <my:NotificationIcon x:Key="notificationIcon" ApplicationExit="notificationIcon_ApplicationExit" />
  </Application.Resources>
</Application>

And App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        FindResource("notificationIcon");
    }

    void notificationIcon_ApplicationExit(object sender, EventArgs eventArgs)
    {
        Application.Current.Shutdown();
    }
}

It looks as if the notificationIcon resource is not being instantiated until I call this code:

FindResource("notificationIcon");

in OnStartup() method. Is there any possibility to write XAML in such a way that this FindResource() call is not needed and that object is instantiated automatically?

Upvotes: 1

Views: 394

Answers (1)

Fede
Fede

Reputation: 44038

public partial class App : Application
{
    public NotificationIcon NotifyIcon {get;set;}

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

        NotifyIcon = new NotificationIcon();
        NotifyIcon.ApplicationExit += notificationIcon_ApplicationExit;
    }

    void notificationIcon_ApplicationExit(object sender, EventArgs eventArgs)
    {
        Application.Current.Shutdown();
    }
}

... And remove it from XAML.

Upvotes: 1

Related Questions