Adding a static object to a resource dictionary

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-21 03:37:35

问题


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:


The accepted answer is wrong, its totally 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);
    }
}


来源:https://stackoverflow.com/questions/5834626/adding-a-static-object-to-a-resource-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!