让我们考虑一个具有以下 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");
在 OnStartup() 方法中。是否有可能以不需要此 FindResource() 调用并且自动实例化该对象的方式编写 XAML?