【问题标题】:Adding a static object to a resource dictionary将静态对象添加到资源字典
【发布时间】:2011-08-15 15:10:00
【问题描述】:

我有一个在多个视图中引用的类,但我希望它们之间只共享一个类的实例。我已经这样实现了我的课程:

using System;

public class Singleton
{
   private static Singleton instance;

   private Singleton() {}

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

有没有办法可以将 Singleton.Instance 作为资源添加到我的资源字典中? 我想写一些类似的东西

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

而不必每次我需要引用它时都写{x:static my:Singleton.Instance}

【问题讨论】:

    标签: wpf mvvm resourcedictionary


    【解决方案1】:

    在 XAML 中是可能的:

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

    【讨论】:

    • 我没有尝试过,但MSDN 似乎建议 应该工作,所以我我只是要接受这个答案。
    • 如果您的目标是将其合并到资源字典中,则不需要密钥。
    【解决方案2】:

    很遗憾,XAML 无法做到这一点。但是您可以将单例对象从代码隐藏添加到资源中:

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e) {
            base.OnStartup(e);
    
            Resources.Add("MySingleton", Singleton.Instance);
        }
    }
    

    【讨论】:

    • 根据 MSDN,StaticExtension 在 .NET Client Profile 3.5 或更低版本中不可用。对于其他版本,请参阅其他答案中的 XAML 版本。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多