Adding a static object to a resource dictionary

2020-06-08 14:37发布

问题:

I have a class which is referenced in multiple views, but I would like there to be only one instance of the class shared among them. I have implemented my class like so:

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

   public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

Is there a way I can add Singleton.Instance to my resource dictionary as a resource? I would like to write something like

<Window.Resources>
    <my:Singleton.Instance x:Key="MySingleton"/>
</Window.Resources>

instead of having to write {x:static my:Singleton.Instance} every time I need to reference it.

回答1:

It is possible in XAML:

<!-- assuming the 'my' namespace contains your singleton -->
<Application.Resources>
   <x:StaticExtension Member="my:Singleton.Instance" x:Key="MySingleton"/>
</Application.Resources>


回答2:

Unfortunately it is not possible from XAML. But you can add the singleton object to the resources from code-behind:

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

        Resources.Add("MySingleton", Singleton.Instance);
    }
}