将静态对象添加到资源字典 [英] Adding a static object to a resource dictionary

查看:45
本文介绍了将静态对象添加到资源字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

有没有办法将 Singleton.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>

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

instead of having to write {x:static my:Singleton.Instance} every time I need to reference it.

推荐答案

在 XAML 中是可能的:

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>

这篇关于将静态对象添加到资源字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆