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.
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.
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.
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.
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>
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With