Reputation: 2746
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
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