让我们考虑使用以下XAML(App.xaml)的WPF应用程序:
<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>
和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();
}
}
在调用此代码之前,看起来好像没有实例化notificationIcon资源:
FindResource("notificationIcon");
答案 0 :(得分:1)
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();
}
}
...并将其从XAML中删除。