强制实例化xaml资源

时间:2013-08-22 20:06:32

标签: c# wpf xaml

让我们考虑使用以下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并自动实例化该对象?

1 个答案:

答案 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中删除。