Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 706
Amanduh Avatar asked Apr 29 '11 16:04

Amanduh


People also ask

How do you add a resource to a dictionary?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1.

What is a static resource WPF?

Static Resource - Static resources are the resources which you cannot manipulate at runtime. The static resources are evaluated only once by the element which refers them during the loading of XAML.

What default resources are supported in WPF?

WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.


2 Answers

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>
like image 145
Jf Beaulac Avatar answered Oct 01 '22 02:10

Jf Beaulac


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);
    }
}
like image 26
Pavlo Glazkov Avatar answered Oct 01 '22 02:10

Pavlo Glazkov