Amanduh
Amanduh

Reputation: 1243

Adding a static object to a resource dictionary

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.

Upvotes: 16

Views: 12526

Answers (2)

Jf Beaulac
Jf Beaulac

Reputation: 5246

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>

Upvotes: 20

Pavlo Glazkov
Pavlo Glazkov

Reputation: 20756

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);
    }
}

Upvotes: 5

Related Questions